synchronized实现的死锁
创建出两个子进程,一个拥有资源A准备获取资源B,另一个拥有资源B准备获取资源A,然后构成死锁。
package com.klaus.thread;
import java.util.concurrent.locks.ReentrantLock;
public class MyDeadLock {
public static void main(String[] args) throws InterruptedException {
Object objA = new Object();
Object objB = new Object();
new Thread(new MakeLock(objA, objB), "ThreadA").start();
new Thread(new MakeLock(objB, objA), "ThreadB").start();
System.out.println("I'm iron man");
}
static class MakeLock extends Thread {
Object objA, objB;
ReentrantLock lock = new ReentrantLock();
ReentrantLock lock2 = new ReentrantLock();
public MakeLock(Object objA, Object objB) {
this.objA = objA;
this.objB = objB;
}
@Override
public void run() {
synchronized (objA) {
System.out.println(Thread.currentThread().getName() + " get an obj");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (objB) {
System.out.println(Thread.currentThread().getName() + " get another obj");
}
}
}
}
}
本文来自博客园,作者:klaus08,转载请注明原文链接:https://www.cnblogs.com/klaus08/p/15357415.html