熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java線程:並發協作-死鎖

2022-06-13   來源: Java核心技術 

    線程發生死鎖可能性很小即使看似可能發生死鎖的代碼在運行時發生死鎖的可能性也是小之又小
 
    發生死鎖的原因一般是兩個對象的鎖相互等待造成的
 
    在《Java線程線程的同步與鎖》一文中簡述死鎖的概念與簡單例子但是所給的例子是不完整的這裡給出一個完整的例子
 



/**
* Java線程並發協作死鎖
*
* @author Administrator ::
*/
public class Test {
        public static void main(String[] args) {
                DeadlockRisk dead = new DeadlockRisk();
                MyThread t = new MyThread(dead );
                MyThread t = new MyThread(dead );
                MyThread t = new MyThread(dead );
                MyThread t = new MyThread(dead );

                tstart();
                tstart();
                tstart();
                tstart();
        }

}

class MyThread extends Thread {
        private DeadlockRisk dead;
        private int a b;


        MyThread(DeadlockRisk dead int a int b) {
                thisdead = dead;
                thisa = a;
                thisb = b;
        }

        @Override
        public void run() {
                deadread();
                deadwrite(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) {
                        Systemoutprintln(read(): + ThreadcurrentThread()getName() + 獲取了resourceA的鎖!);
                        synchronized (resourceB) {
                                Systemoutprintln(read(): + ThreadcurrentThread()getName() + 獲取了resourceB的鎖!);
                                return resourceBvalue + resourceAvalue;
                        }
                }
        }

        public void write(int a int b) {
                synchronized (resourceB) {
                        Systemoutprintln(write(): + ThreadcurrentThread()getName() + 獲取了resourceA的鎖!);
                        synchronized (resourceA) {
                                Systemoutprintln(write(): + ThreadcurrentThread()getName() + 獲取了resourceB的鎖!);
                                resourceAvalue = a;
                                resourceBvalue = b;
                        }
                }
        }
}
 
下面死鎖的情況發生了真是難得一見啊

  


 
    本文出自 熔 巖 博客請務必保留此出處
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26504.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.