package test;
/**
* 线程测试二 死锁
* @author 郭胜
*
*/
public class ThreadTestTwo {
public static void main(String[] args){
Object obj1 = new Object();
Object obj2 = new Object();
Test1 t1 = new Test1(true,obj1,obj2);
Test1 t2 = new Test1(false,obj1,obj2);
Thread tt1 = new Thread(t1);
Thread tt2 = new Thread(t2);
tt1.start();
tt2.start();
}
}
class Test1 implements Runnable{
private Object obj1;
private Object obj2;
boolean flag;
public Test1(boolean flag,Object obj1,Object obj2){
this.flag = flag;
this.obj1 = obj1;
this.obj2 = obj2;
}
public void run() {
while(true){
if(flag){
synchronized(obj1){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"…………………………obj1 锁1");
synchronized(obj2){
System.out.println(Thread.currentThread().getName()+"……………………obj2锁2");
}
}
}else{
synchronized(obj2){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"……………………obj2锁2");
synchronized(obj1){
System.out.println(Thread.currentThread().getName()+"…………………………obj1 锁1");
}
}
}
}
}
}
java线程锁死小demo
最新推荐文章于 2023-08-17 17:28:56 发布