赞
踩
可以使用Semaphore信号量,记录拥有该资源线程的个数。
public static final Semaphore semaphore1 = new Semaphore(1,false);//表示只能一个线程进入
代码如下;
- import java.util.concurrent.CountDownLatch;
- import java.util.concurrent.Semaphore;
- import java.util.concurrent.TimeUnit;
-
- public class DeadLockWithSemaphore {
-
- public static String obj1 = "obj1";//资源1
- public static final Semaphore semaphore1 = new Semaphore(1,false);//fair(FIFO),false unfair
- public static String obj2 = "obj2";//资源2
- public static final Semaphore semaphore2 = new Semaphore(1,false);
- public static void main(String[] args) throws Exception{
- final CountDownLatch countdown = new CountDownLatch(1);
- new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- countdown.await();//都进入等待
- while (true) {
- if (semaphore1.tryAcquire(1, TimeUnit.SECONDS)) {
- synchronized (DeadLock.obj1) {
- System.out.println(Thread.currentThread() + "has lock obj1");
- Thread.sleep(3000);//获取obj1后先等一会儿,让Lock2有足够的时间锁住obj2
- System.out.println(Thread.currentThread() + "ready to lock obj2");
- if (semaphore2.tryAcquire(1, TimeUnit.SECONDS)) {
- synchronized (DeadLock.obj2) {
- System.out.println(Thread.currentThread() + "has lock obj2(second Lock)");
- }
- semaphore2.release();//先释放内部资源
- semaphore1.release();//再释放外部资源
- break;
- }
- }
- //执行这里说明:已拥有1资源,但未同时拥有2号资源
- semaphore1.release();//释放1资源
- }
- }
- }catch (Exception e) {
- e.printStackTrace();
- }
- }
- },"thread1" ).start();
-
- new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- countdown.await();//都进入等待
- while (true){
- if(semaphore2.tryAcquire(1, TimeUnit.SECONDS)) {
- synchronized (DeadLock.obj2) {
- System.out.println(Thread.currentThread() + "has lock obj2");
- Thread.sleep(3000);//获取obj1后先等一会儿,让Lock2有足够的时间锁住obj2
- System.out.println(Thread.currentThread() + "ready to lock obj1");
- if(semaphore1.tryAcquire(1, TimeUnit.SECONDS)) {
- synchronized (DeadLock.obj1) {
- System.out.println(Thread.currentThread() + "has lock obj1(second Lock)");
- semaphore1.release();//先释放内部资源
- semaphore2.release();//再释放外部资源
- break;
- }
- }
- }
- //执行这里说明:已拥有2资源,但未同时拥有1号资源
- semaphore2.release();//释放2资源
- // 这里只是为了演示,所以tryAcquire只用1秒,而且2要给1让出能执行的时间,否则两个永远是死锁
- Thread.sleep(10 * 1000);
- }
- }
- }catch (Exception e) {
- e.printStackTrace();
- }
- }
- },"thread2" ).start();
- countdown.countDown();
- }
-
- }

执行结果如下:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。