public class DeadLock {
public static String resource1 = "resource1";
public static String resource2 = "resource2";
public static void main(String[] args){
Thread thread1 = new Thread(new One());
Thread thread2 = new Thread(new Two());
thread1.start();
thread2.start();
}
static class One implements Runnable {
@Override
public void run() {
try{
System.out.println("Thread1启动");
while(true){
synchronized(DeadLock.resource1){
System.out.println("Thread1拿到了resource1的锁");
Thread.sleep(3000);//获取resource1后先等一会儿,让Thread2有足够的时间锁住resource2
System.out.println("Thread1想拿resource2的锁。。。。");
synchronized(DeadLock.resource2){
System.out.println("Thread1获得到了resource2的锁");
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
static class Two implements Runnable {
@Override
public void run(){
try{
System.out.println("Thread2启动");
while(true){
synchronized(DeadLock.resource2){
System.out.println("Thread2拿得到了resource2的锁");
Thread.sleep(3000);//获取resource2后先等一会儿,让Thread1有足够的时间锁住resource1
System.out.println("Thread2想拿resource1的锁。。。。");
synchronized(DeadLock.resource1){
System.out.println("Thread2获得到了resource1的锁");
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
}
Java 死锁范例
最新推荐文章于 2020-12-03 09:46:18 发布