理解 wait()
我创建了这个愚蠢的程序来玩 wait()
public class WaitTest {
public static void main(String [] args) {
System.out.print("1 ");
synchronized(args){
System.out.print("2 ");
try {
args.wait();
args.notifyAll();
}
catch(InterruptedException e){ System.out.print("exception caught");}
System.out.print("3 ");
}
}
}
在我的机器上,代码永远不会打印 3,除非我写 wait(100)
或其他毫秒数。这是为什么呢?
I created this silly program to play with wait()
public class WaitTest {
public static void main(String [] args) {
System.out.print("1 ");
synchronized(args){
System.out.print("2 ");
try {
args.wait();
args.notifyAll();
}
catch(InterruptedException e){ System.out.print("exception caught");}
System.out.print("3 ");
}
}
}
On my machine, the code never gets to print 3, unless I write wait(100)
or another number of milliseconds. Why is this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您正在 wait() 之前执行 notificationAll()。 wait() 将被阻塞。当您输入超时值时, wait() 将超时,然后您的程序将继续。如果您希望程序正常工作,请创建一个线程并在那里执行 notificationAll() 。 wait() 和notifyAll 是为线程间同步而设计的。
You are doing the wait() before the notifyAll(). wait() is going to block. When you put the timeout value in, wait() will timeout and then your program will continue. If you want your program to work, create a thread and do your notifyAll() there. wait() and notifyAll are designed for interthread synchronization.
wait
和notifyAll
用于多线程。args.wait()
将永远等待,直到其他线程调用args.notifyAll()
或args.notify().
当您调用 args.wait(100) 时,它会等待 100 毫秒,超时并继续。
如果您熟悉信号量,那么这基本上就是等待/通知。
wait
andnotifyAll
are for multithreading.args.wait()
will wait forever until some other thread callsargs.notifyAll()
orargs.notify()
.When you call
args.wait(100)
, it is waiting for 100ms, timing out, and continuing.If you are familiar with semaphores, that is basically what wait/notify are.
你只有一个线程。 wait() 正在等待来自另一个线程的通知。
You only have one thread. wait() is waiting for a notify from another thread.
由于没有其他线程通知您正在等待的对象监视器,因此它只是阻塞在那里。由于您正在同步并等待局部变量,因此几乎任何其他线程都无法对其调用
notify()
。Since no other thread notifies the object's monitor you are waiting on, it is just blocking there. And since you are synchronizing and waiting on a local variable, hardly any other thread would be able to call
notify()
on it.来自 http://java.sun.com/docs/books /tutorial/essential/concurrency/guardmeth.html
Java 教程是一个极好的学习资源。
From http://java.sun.com/docs/books/tutorial/essential/concurrency/guardmeth.html
The Java Tutorial is an excellent learning resource.