class Zhangsan {
public void say(){
System.out.println("张三对李四说:你把画给我,我把书给你");
}
public void get(){
System.out.println("张三得到了画");
}
}
class Lisi {
public void say(){
System.out.println("李四对张三说:你把书给我,我把画给你");
}
public void get(){
System.out.println("李四得到了书");
}
}
public class T2 implements Runnable{
private static Zhangsan zs = new Zhangsan();
private static Lisi ls = new Lisi();
private boolean flag = false;
@Override
public void run(){
if(flag){
synchronized(zs){
zs.say();
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
synchronized(ls){
zs.get();
}
}
}else{
synchronized(ls){
ls.say();
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
synchronized(zs){
ls.get();
}
}
}
}
public static void main(String[] args){
T2 t1 = new T2();
T2 t2 = new T2();
t1.flag = true;
t2.flag = false;
Thread th1 = new Thread(t1);
Thread th2 = new Thread(t2);
th1.start();
th2.start();
}
}