我正在尝试 java.lang.Object 中 wait() 的定时版本,并观察到它在两种不同场景中的行为有所不同。
场景1:使用Thread中run()的默认定义
public static void main (String[] args) throws InterruptedException {
Thread t = new Thread();
t.start();
System.out.print("X");
synchronized(t) { t.wait(10000);}
System.out.print("Y");
}
关于场景1的问题:我在 X 和 Y 之间遇到延迟。这是因为我从 main 调用 wait() (即使在 t 上),因此正在使用主线程的调用堆栈,而不是第二个线程的调用堆栈?
场景2: 动态子类化 Thread 以覆盖 run() 以打印某些内容。
public static void main (String[] args) throws InterruptedException {
Thread t = new Thread() {public void run()
{System.out.print("I am the second thread.");}};
t.start();
System.out.print("X");
synchronized(t) { t.wait(10000);}
System.out.print("Y");
}
关于场景2的问题:我根本没有遇到任何延迟!仅仅因为我重写了 run() 就发生了什么变化?现在,每次我运行该程序时,它都会立即打印“XI am the secondary thread.Y”,没有任何延迟! wait()的作用去哪儿了?
你实际上已经明白了为什么你永远不应该打电话wait
or notify(All)
关于线程(请参阅 JavaDocs for Thread)。在内部,Thread使用wait和notifyAll来实现Thread.join(),所以第二种情况发生的是你的线程进入wait,但随后另一个线程死亡并调用notifyAll(),这会唤醒你的主线程。
Use Thread.sleep
如果您只想等待一段时间,请使用Thread.join
如果您确实想等待线程终止。另外,请阅读 javadocsObject
为了正确使用wait
, notify
, and notifyAll
.
javaDoc:
public final void join(long millis)
throws InterruptedException
最多等待 millis 毫秒该线程终止。超时时间为
0 表示永远等待。此实现使用 this.wait 循环
调用以 this.isAlive 为条件。当一个线程终止时
this.notifyAll 方法被调用。建议申请
不要在 Thread 实例上使用 wait、notify 或 notifyAll。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)