死锁是一种状态,当两个线程互相持有对象所需要的资源的时候,这两个线程又都不主动释放资源
就会导致死锁。代码无法正常执行。这两个线程就会僵持住。
class DeadLock implements Runnable {
private boolean flag;//标记
private Object obj1;//对象1
private Object obj2;//对象2
public DeadLock(boolean flag, Object obj1, Object obj2) {
this.flag = flag;
this.obj1 = obj1;
this.obj2 = obj2;
}
@Override
public void run() {
if (flag) {//如果flag = true 让线程1执行这个if语句里面的代码
synchronized (obj1) {
System.out.println(Thread.currentThread().getName() + "拿到了obj1资源");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程1执行了");
synchronized (obj2) {//想用obj2这个资源
System.out.println(Thread.currentThread().getName() + "拿到obj2资源");
}
}
}
if (!flag) {//如果flag=false 线程2 执行这个if语句里面的代码
synchronized (obj2) {
System.out.println(Thread.currentThread().getName() + "拿到了obj2资源");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程2执行了");
synchronized (obj1) {
System.out.println(Thread.currentThread().getName() + "拿到obj1资源");
}
}
}
}
}
public class Demo1 {
public static void main(String[] args) {
Object obj1 = new Object();
Object obj2 = new Object();
DeadLock deadLock1 = new DeadLock(true, obj1, obj2);
new Thread(deadLock1, "线程1").start();
DeadLock deadLock2 = new DeadLock(false, obj1, obj2);
new Thread(deadLock2, "线程1").start();
}
}