[javaSE] 並發編程(線程間通訊),javase線程

來源:互聯網
上載者:User

[javaSE] 並發編程(線程間通訊),javase線程

建立一個資源類Resource

定義成員變數String name

定義成員變數int age

 

建立一個輸入類Input,實現Runnable介面

定義一個構造方法Input(),傳入參數:Resource對象

實現run()方法

定義while(true)往Resuorce對象的屬性賦值

 

 

建立一個輸出類Output,實現Runnable介面

定義一個構造方法Output(),傳入參數:Resource對象

實現run()方法

定義while(true)列印Resuorce對象的屬性

 

 

main方法中

擷取Resource對象,new出來

擷取Input對象,new出來,構造參數:Resource對象

擷取Output對象,new出來,構造參數:Resource對象

擷取Thread對象,new出來,構造參數:Runnable對象

調用Thread對象的start()方法,開啟線程

 

此時會有安全執行緒問題,查看結果可以發現,漢字和拼音的混了

陶士涵=====男

taoshihan=====nan

陶士涵=====nan

陶士涵=====nan

陶士涵=====男

陶士涵=====男

陶士涵=====nan

陶士涵=====nan

taoshihan=====nan

taoshihan=====nan

 

使用synchronized(){}同步代碼塊包裹操作同一個資源的地方

注意同步線程的個數,所有的線程都應該加上

注意是否是同一個鎖,synchronized()括弧內的鎖參數:保證是個唯一的資源

使用synchronized(){}包裹上面的賦值和列印,鎖:Resource對象(唯一的)

 

查看結果,此時沒有安全問題

陶士涵=====男

陶士涵=====男

陶士涵=====男

taoshihan=====nan

taoshihan=====nan

taoshihan=====nan

 

死結問題:同步中嵌套同步,並且鎖不一致,此時會造成死結問題

/** * 資源 *  * @author taoshihan *  */class Resource {    String name;    String sex;}/** * 輸入 *  * @author taoshihan *  */class Input implements Runnable {    private Resource resource;    public Input(Resource resource) {        this.resource = resource;    }    @Override    public void run() {        // 切換        boolean flag = true;        while (true) {            synchronized (resource) {                if (flag) {                    resource.name = "taoshihan";                    resource.sex = "nan";                } else {                    resource.name = "陶士涵";                    resource.sex = "男";                }                flag = !flag;            }        }    }}/** * 輸出 *  * @author taoshihan *  */class Output implements Runnable {    private Resource resource;    public Output(Resource resource) {        this.resource = resource;    }    @Override    public void run() {        while (true) {            synchronized (resource) {                System.out.println(resource.name + "=====" + resource.sex);            }        }    }}public class InputOutputDemo {    /**     * @param args     */    public static void main(String[] args) {        Resource resource = new Resource();        Input input = new Input(resource);        Output output = new Output(resource);        Thread t1 = new Thread(input);        Thread t2 = new Thread(output);        t1.start();        t2.start();    }}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.