package thread;
/**
* JAVA多线程 死锁程序
* @author hero
*
*/
class TestLock implements Runnable {
private boolean flag;
TestLock(boolean flag){
this.flag = flag;
}
public void run() {
if(flag){
while(true){
synchronized (MyLock.locka) {
//进入拿到A锁--等待B锁
System.out.println("if locka");
synchronized (MyLock.lockb) {
System.out.println("if lockb");
}
}
}
}else{
while(true){
synchronized (MyLock.lockb) {
//进入 拿到B锁--等待A锁
System.out.println("else lockb");
synchronized (MyLock.locka) {
System.out.println("else locka");
}
}
}
}
}
}
class MyLock{//锁类
static Object locka = new Object();
static Object lockb = new Object();
}
public class DeadLockTest8 {
/**
* @param args
*/
public static void main(String[] args) {
Thread t1 = new Thread(new TestLock(true));//拿A锁--等B锁
Thread t2 = new Thread(new TestLock(false));//拿B锁--等A锁
t1.start();
t2.start();
}
}
JAVA多线程死锁程序Demo
最新推荐文章于 2023-04-02 23:10:04 发布