62,615
社区成员
发帖
与我相关
我的任务
分享
final Object completeSignal = new Object();
Thread thread = new Thread("worker-thread") {
public void run() {
try {
Thread.sleep(3000);
System.out.println("执行");
} catch (Exception e) {
e.printStackTrace();
}
synchronized (completeSignal) {
completeSignal.notifyAll();
}
}
};
synchronized (completeSignal) {
thread.start();
completeSignal.wait();
System.out.println("执行完了");
}
[/quote]
很明显你在main线程中调用了completeSignal.wait(); wait与sleep方法时有区别的两者都会使得线程挂起但是wait会释放锁。final Object completeSignal = new Object();
Thread thread = new Thread("worker-thread") {
public void run() {
try {
Thread.sleep(3000);
System.out.println("执行");
} catch (Exception e) {
e.printStackTrace();
}
synchronized (completeSignal) {
completeSignal.notifyAll();
}
}
};
synchronized (completeSignal) {
thread.start();
completeSignal.wait();
System.out.println("执行完了");
}