代码-JavaSE-多线程-一个死锁示例

package ceshi.duoxiancheng.sisuo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Demo {
public static void main(String[] args) {
RunnableA_1 r1 = new RunnableA_1();
RunnableA_2 r2 = new RunnableA_2();

Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);

t1.start();
t2.start();
}

}

class A {
final static Lock LOCK1=new ReentrantLock();
final static Lock LOCK2=new ReentrantLock();

static void show1() {
LOCK1.lock();
{
LOCK2.lock();
System.out.println("show1..");
LOCK2.unlock();
}
LOCK1.unlock();
}

static void show2() {
LOCK2.lock();
{
LOCK1.lock();
System.out.println("show2...");
LOCK1.unlock();
}
LOCK2.unlock();
}
}

class RunnableA_1 implements Runnable {
public void run() {
while (true) {
A.show1();
}
}
}

class RunnableA_2 implements Runnable {
public void run() {
while (true) {
A.show2();
}
}
}

猜你喜欢

转载自www.cnblogs.com/wonewo/p/9440172.html