当前位置:   article > 正文

Java多线程之间引发死锁问题(2)_public static final semaphore homepermit = new sem

public static final semaphore homepermit = new semaphore(1, true);

可以使用Semaphore信号量,记录拥有该资源线程的个数。

public static final Semaphore semaphore1 = new Semaphore(1,false);//表示只能一个线程进入

代码如下;

  1. import java.util.concurrent.CountDownLatch;
  2. import java.util.concurrent.Semaphore;
  3. import java.util.concurrent.TimeUnit;
  4. public class DeadLockWithSemaphore {
  5. public static String obj1 = "obj1";//资源1
  6. public static final Semaphore semaphore1 = new Semaphore(1,false);//fair(FIFO),false unfair
  7. public static String obj2 = "obj2";//资源2
  8. public static final Semaphore semaphore2 = new Semaphore(1,false);
  9. public static void main(String[] args) throws Exception{
  10. final CountDownLatch countdown = new CountDownLatch(1);
  11. new Thread(new Runnable() {
  12. @Override
  13. public void run() {
  14. try {
  15. countdown.await();//都进入等待
  16. while (true) {
  17. if (semaphore1.tryAcquire(1, TimeUnit.SECONDS)) {
  18. synchronized (DeadLock.obj1) {
  19. System.out.println(Thread.currentThread() + "has lock obj1");
  20. Thread.sleep(3000);//获取obj1后先等一会儿,让Lock2有足够的时间锁住obj2
  21. System.out.println(Thread.currentThread() + "ready to lock obj2");
  22. if (semaphore2.tryAcquire(1, TimeUnit.SECONDS)) {
  23. synchronized (DeadLock.obj2) {
  24. System.out.println(Thread.currentThread() + "has lock obj2(second Lock)");
  25. }
  26. semaphore2.release();//先释放内部资源
  27. semaphore1.release();//再释放外部资源
  28. break;
  29. }
  30. }
  31. //执行这里说明:已拥有1资源,但未同时拥有2号资源
  32. semaphore1.release();//释放1资源
  33. }
  34. }
  35. }catch (Exception e) {
  36. e.printStackTrace();
  37. }
  38. }
  39. },"thread1" ).start();
  40. new Thread(new Runnable() {
  41. @Override
  42. public void run() {
  43. try {
  44. countdown.await();//都进入等待
  45. while (true){
  46. if(semaphore2.tryAcquire(1, TimeUnit.SECONDS)) {
  47. synchronized (DeadLock.obj2) {
  48. System.out.println(Thread.currentThread() + "has lock obj2");
  49. Thread.sleep(3000);//获取obj1后先等一会儿,让Lock2有足够的时间锁住obj2
  50. System.out.println(Thread.currentThread() + "ready to lock obj1");
  51. if(semaphore1.tryAcquire(1, TimeUnit.SECONDS)) {
  52. synchronized (DeadLock.obj1) {
  53. System.out.println(Thread.currentThread() + "has lock obj1(second Lock)");
  54. semaphore1.release();//先释放内部资源
  55. semaphore2.release();//再释放外部资源
  56. break;
  57. }
  58. }
  59. }
  60. //执行这里说明:已拥有2资源,但未同时拥有1号资源
  61. semaphore2.release();//释放2资源
  62. // 这里只是为了演示,所以tryAcquire只用1秒,而且2要给1让出能执行的时间,否则两个永远是死锁
  63. Thread.sleep(10 * 1000);
  64. }
  65. }
  66. }catch (Exception e) {
  67. e.printStackTrace();
  68. }
  69. }
  70. },"thread2" ).start();
  71. countdown.countDown();
  72. }
  73. }

执行结果如下:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/721051
推荐阅读
相关标签
  

闽ICP备14008679号