關於實現Runnable介面的類中有公用屬性問題

來源:互聯網
上載者:User

標籤:code   安全執行緒   main   ring   comm   override   .exe   span   runnable   

背景:多線程開發的時候,一般都是繼承Runnable介面,但是有可能類中有一個公開變數,那麼這個變數是不是安全執行緒的呢?

代碼如下:

public class TestThread implements Runnable{    private int number = 0;    public TestThread(int num) {        number = num;    }    @Override    public void run() {        for(int i = 0;i<10;i++) {            System.out.println("當前線程為:"+Thread.currentThread().getName()+",num="+(number++));        }    }}

當使用線程池進行操作時,可以分為2種情況。

1,共用某一種元素

2,不想共用某一個元素

代碼如下:

1,

public class Test {    public static void main(String[] args) {        TestThread t = new TestThread(0);        for(int i = 0;i<10;i++) {            CommonThreadPool.getInstance().getFixedThreadPool().execute(t);        }    }}

此種寫法會有多線程問題,因為共用了一個元素

2,

public class Test {    public static void main(String[] args) {//        TestThread t = new TestThread(0);        for(int i = 0;i<10;i++) {            CommonThreadPool.getInstance().getFixedThreadPool().execute(new TestThread(0));        }    }}

此種寫法某種程度來說不會有多線程問題,因為new對象之後並沒有共用同一個元素

如果想避免某一些問題,那麼可以加鎖看來控制,如:

public class TestThread implements Runnable{    private int number = 0;    public TestThread(int num) {        number = num;    }    @Override    public synchronized void run() {        for(int i = 0;i<10;i++) {            System.out.println("當前線程為:"+Thread.currentThread().getName()+",num="+(number++));        }    }}

以上只是樣本一下,因為加鎖的地方是要看具體的情況的。

所以,最初的這段代碼:

public class TestThread implements Runnable{    private int number = 0;    public TestThread(int num) {        number = num;    }    @Override    public void run() {        for(int i = 0;i<10;i++) {            System.out.println("當前線程為:"+Thread.currentThread().getName()+",num="+(number++));        }    }}

其實某種程度上來說並不安全,因為依賴於外部的調用方式。

 

關於實現Runnable介面的類中有公用屬性問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.