1.死锁 :
public class 死锁 {
public static String left="左边筷子";
public static String right="右边筷子";
public static void main(String[] args) {
Thread n1 = new Thread() {
public void run() {
//锁住右边筷子
synchronized(right) {
System.out.println(Thread.currentThread().getName()+"抢到右边筷子了");
System.out.println(Thread.currentThread().getName()+"准备开始抢左边筷子!");
synchronized(left) {//需要的左边筷子 在以下线程2那未释放
//无法进入
}
}
}
};
Thread n2 = new Thread() {
public void run() {
//锁住左边筷子
synchronized(left) {//需要的右边筷子 在以上线程1那未释放
System.out.println(Thread.currentThread().getName()+"抢到左边筷子了");
System.out.println(Thread.currentThread().getName()+"准备开始抢右边筷子!");
synchronized(right) {
//无法进入
}
}
}
};
n1.setName("小黑");n1.start();
n2.setName("大黄");n2.start();
}
}