问题描述
Thread t2 = new Thread();
Thread t3 = new Thread();
t1.start();
t2.start();
synchronized (t2) {
t2.wait(20000);
}
t3.start();
上面的程序在不等待t2的情况下运行20秒。我观察到,当线程对象启动时,它将不会等待。为什么会这样?
解决方法
为什么会这样?
首先,让我们澄清一下。 t2.wait(20000)
这个函数调用对t2
线程没有任何作用。实际上,它根本不执行任何操作。它所做的就是不返回,直到发生两种情况之一;
- 其他一些线程调用
t2.notify()
或 - 经过20秒。
如果调用返回不到20秒,则可能是因为t2
线程本身在死亡之前调用了t2.notify()
。在Java标准库的大多数实现中,join()
方法是通过在线程对象上使用wait()
和notify()
调用来实现的。
(注意:大多数作者会建议您不要永远不要在Thread实例上调用wait()
或notify()
,因为您的代码和库之间可能存在干扰两者在相同实例上调用相同方法时的代码。)
上面的程序无需t2等待20秒即可运行。
正如其他人已经在此处指出的那样,您尚未为run()
线程提供任何t2
方法,因此目前尚不清楚为什么您期望t2
线程“等待”或者,做其他任何事情。线程做的唯一一件事就是执行您在run()
方法中为其提供的代码。
默认的Thread.run()
方法将调用构造线程时提供的 delegate 对象的run()
方法,但是代码不提供委托。在这种情况下,默认的run()方法什么也不做。
使用sleep
暂停线程,而无需完成工作。
wait
不会暂停线程,它只是等待线程完成(并且该线程已经完成)。
class SleepThread extends Thread {
//run method for thread
public void run() {
for(int i=1;i<5;i++) {
try {
//call sleep method of thread
Thread.sleep(20000);
}catch(InterruptedException e){
System.out.println(e);
}
//print current thread instance with loop variable
System.out.println(Thread.currentThread().getName() + " : " + i);
}
}
}
class Main{
public static void main(String args[]){
//create two thread instances
SleepThread thread_1 = new SleepThread();
SleepThread thread_2 = new SleepThread();
//start threads one by one
thread_1.start();
thread_2.start();
}
}