程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java線程:並發協作-死鎖

Java線程:並發協作-死鎖

編輯:關於JAVA

發生死鎖的原因一般是兩個對象的鎖相互等待造成的。

在《Java線程:線程的同步與鎖》一文中,簡述死鎖的概念與簡單例子,但是所給的例子是不完整的,這裡給出一個完整的例子。

/**
* Java線程:並發協作-死鎖
*
* @author Administrator
*/
public class Test {
         public static void main(String[] args) {
                 DeadlockRisk dead = new DeadlockRisk();
                 MyThread t1 = new MyThread(dead, 1, 2);
                 MyThread t2 = new MyThread(dead, 3, 4);
                 MyThread t3 = new MyThread(dead, 5, 6);
                 MyThread t4 = new MyThread(dead, 7, 8);
                 t1.start();
                 t2.start();
                 t3.start();
                 t4.start();
         }
}
class MyThread extends Thread {
         private DeadlockRisk dead;
         private int a, b;

         MyThread(DeadlockRisk dead, int a, int b) {
                 this.dead = dead;
                 this.a = a;
                 this.b = b;
         }
         @Override
         public void run() {
                 dead.read();
                 dead.write(a, b);
         }
}
class DeadlockRisk {
         private static class Resource {
                 public int value;
         }
         private Resource resourceA = new Resource();
         private Resource resourceB = new Resource();
         public int read() {
                 synchronized (resourceA) {
                         System.out.println("read():" + Thread.currentThread().getName() + "獲取了resourceA的鎖!");
                         synchronized (resourceB) {
                                 System.out.println("read():" + Thread.currentThread().getName() + "獲取了resourceB的鎖!");
                                 return resourceB.value + resourceA.value;
                         }
                 }
         }
         public void write(int a, int b) {
                 synchronized (resourceB) {
                         System.out.println("write():" + Thread.currentThread().getName() + "獲取了resourceA的鎖!");
                         synchronized (resourceA) {
                                 System.out.println("write():" + Thread.currentThread().getName() + "獲取了resourceB的鎖!");
                                 resourceA.value = a;
                                 resourceB.value = b;
                         }
                 }
         }
}

下面死鎖的情況發生了,真是難得一見啊:

出處:http://lavasoft.blog.51cto.com/62575/222074

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved