在 Java 中调用 wait() 后线程会做什么? [英] What does a thread do after calling wait() in Java?

查看:59
本文介绍了在 Java 中调用 wait() 后线程会做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在多线程程序中,我怀疑当一个线程wait()时,它并没有占用太多的cpu利用率,以便cpu可以交换来处理其他线程.

In multi-threading programs, I suspect that when a thread wait(), it does not engage much cpu utilization so that the cpu can swap to process other thread.

例如,100 个线程一起启动相同的任务,而 50 个线程实际执行任务,而其他 50 个线程等待所有 50 个任务完成.后一种情况比前一种情况花费的时间少得多.

For example, 100 threads start the same task together comparing to 50 threads actually do the task while other 50 threads wait until all 50 tasks are completed. The latter case cost much less time than the former.

有人可以推荐一些关于此的阅读资料吗?

Can anyone suggest some readings about this?

推荐答案

wait 方法有两个目的:

The wait method has two purposes:

  1. 它会告诉当前正在执行的线程进入睡眠状态(不使用任何 CPU).
  2. 它将释放锁,以便其他线程可以唤醒并获取锁.

每当一个方法在同步块中执行某些操作时,块中的任何内容都必须等待锁定的对象被释放.

Whenever a method does something inside a synchronized block, whatever is in the block must wait for the locked object to be released.

synchronized (lockObject) {
    // someone called notify() after taking the lock on
    // lockObject or entered wait() so now it's my turn

    while ( whatineedisnotready) {
        wait(); // release the lock so others can enter their check
        // now, if there are others waiting to run, they 
        // will have a chance at doing so.
    }
}

必读:

java 同步

这篇关于在 Java 中调用 wait() 后线程会做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆