public class TestDaedLock {
public static void main(String[] args) {
LeftChopstick left = new LeftChopstick();
RightChopstick right = new RightChopstick();
Thread boy = new Thread(new Boy(left,right));
Thread girl= new Thread(new Girl(left,right));
boy.start();
girl.start();
}
}
class LeftChopstick{
String name = "左筷子";
}
class RightChopstick{
String name = "有筷子";
}
class Boy implements Runnable{
LeftChopstick left;
RightChopstick right;
public Boy(LeftChopstick left, RightChopstick right) {
super();
this.left = left;
this.right = right;
}
public void run() {
System.out.println("男孩要拿筷子");
synchronized(left) {
System.out.println("男孩拿到了左筷子,开始拿右筷子");
try {
left.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized(right) {
System.out.println("男孩拿到了右筷子,开始吃饭");
}
}
}
}
class Girl implements Runnable{
LeftChopstick left;
RightChopstick right;
public Girl(LeftChopstick left, RightChopstick right) {
super();
this.left = left;
this.right = right;
}
public void run() {
System.out.println("女孩要拿筷子");
synchronized(right) {
System.out.println("女孩拿到了右筷子,开始拿左筷子");
synchronized(left) {
System.out.println("女孩拿到了左筷子,开始吃饭");
left.notify();
}
}
}
}
运行结果;