【发布时间】:2010-03-23 12:38:42
【问题描述】:
我有以下代码,我预计在打印出“主要:预同步”后会死锁。但看起来synchronized 并没有达到我的预期。这里发生了什么?
import java.util.*;
public class deadtest {
public static class waiter implements Runnable {
Object obj;
public waiter(Object obj) {
this.obj = obj;
}
public void run() {
System.err.println("Thead: pre-sync");
synchronized(obj) {
System.err.println("Thead: pre-wait");
try {
obj.wait();
} catch (Exception e) {
}
System.err.println("Thead: post-wait");
}
System.err.println("Thead: post-sync");
}
}
public static void main(String args[]) {
Object obj = new Object();
System.err.println("Main: pre-spawn");
Thread waiterThread = new Thread(new waiter(obj));
waiterThread.start();
try {
Thread.sleep(1000);
} catch (Exception e) {
}
System.err.println("Main: pre-sync");
synchronized(obj) {
System.err.println("Main: pre-notify");
obj.notify();
System.err.println("Main: post-notify");
}
System.err.println("Main: post-sync");
try {
waiterThread.join();
} catch (Exception e) {
}
}
}
由于两个线程在创建的对象上同步,我希望线程实际上会相互阻塞。目前,代码愉快地通知其他线程,加入和退出。
【问题讨论】:
标签: java multithreading synchronization deadlock