题
写一个线程死锁demo
解
思路
创建两个资源变量; 创建两个线程;
线程1先获取并锁定资源1,休眠一段时间再获取并锁资源2;
线程2先获取并锁定资源2,休眠一段时间再获取并锁资源1;
由于资源1已经被线程1锁定,线程2无法获取; 由于资源2已经被线程2锁定,线程1无法获取; 造成死锁。
代码
public class DeadClockDemo {
private static final Object val1=1;
private static final Object val2=2;
private static class Thread1 extends Thread{
@Override
public void run(){
synchronized (val1){ //读取并锁val1
try {
System.out.println(Thread.currentThread()+" get val1");
System.out.println(Thread.currentThread()+" is waiting val2");
Thread.sleep(5000); //线程休眠
synchronized (val2){ //读取并锁val2
System.out.println(Thread.currentThread()+" get val2");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private static class Thread2 extends Thread{
@Override
public void run(){
synchronized (val2){ //读取并锁val2
try {
System.out.println(Thread.currentThread()+" get val2");
System.out.println(Thread.currentThread()+" is waiting val1");
Thread.sleep(5000);
synchronized (val1){ //读取并锁 val1
System.out.println(Thread.currentThread()+" get val1");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
//启动线程
new Thread1().start();
new Thread2().start();
}
}