一手给钱一手给货;
你不给钱,我不给货;
你不给货,我不给钱;
这就是死锁。
package com.ljl.thread;
public class SynDemo3 {
public static void main(String[] args) {
Object g=new Object();
Object m=new Object();
//真实角色(2个线程准备访问同一份资源)
Test test1=new Test(g,m);
Test2 test2=new Test2(g,m);
//代理角色
Thread proxy=new Thread(test1);
Thread proxy2=new Thread(test2);
proxy.start();
proxy2.start();
}
}
class Test implements Runnable{
Object goods;
Object money;
public Test(Object goods, Object money) {
super();
this.goods = goods;
this.money = money;
}
@Override
public void run() {
while(true) {
test();
}
}
public void test() {
synchronized (goods) {
try {
Thread.sleep(500);//放大发生错误的可能性
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (money) {
}
System.out.println("一手给钱");
}
}
}
class Test2 implements Runnable{
Object goods;
Object money;
public Test2(Object goods, Object money) {
super();
this.goods = goods;
this.money = money;
}
@Override
public void run() {
while(true) {
test();
}
}
public void test() {
synchronized (money) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (goods) {
}
System.out.println("一手给货");
}
}
}