jdk1.5以後的多線程同步方式

來源:互聯網
上載者:User

jdk1.5以後有了java.util.concurrent包

裡面對同步提供了相當多的支援

例如lock atomic以及一些可同步操作的容器

下面給出一個常見的多線程面試題及其對應實現

有三個線程ID分別是A、B、C,請有多線編程實現,在螢幕上迴圈列印10次ABCABC

採用AtomicInteger來實現這個,

不多說了,上代碼,還是相當簡單易懂的

可以對concurrent包見一斑。

   1. import java.util.concurrent.atomic.AtomicInteger;     2.      3. public class Print extends Thread{     4.     //專門為同步用的 用integer不行,每次都會建立的     5.     private AtomicInteger synObj;     6.     private int count;     7.     private String s;     8.     private int flag;     9.     private int total = 0;    10.         11.     public Print(int count,AtomicInteger atomicInteger,String s,int flag) {    12.         this.count = count;    13.         this.synObj = atomicInteger;    14.         this.s = s;    15.         this.flag = flag;    16.     }    17.     public void run() {    18.         while(true) {    19.             synchronized(synObj) {    20.                 if(synObj.intValue()%3 == flag) {    21.                     total++;    22.                     synObj.set(synObj.intValue()+1);    23.                     System.out.println(s);    24.                     synObj.notifyAll();    25.                     if(total == count) {    26.                         break;    27.                     }    28.                 }else {    29.                     try{    30.                         synObj.wait();    31.                     }catch(Exception e){    32.                         e.printStackTrace();    33.                     }    34.                 }    35.             }    36.         }    37.     }    38.     public static void main(String[]args) throws Exception {    39.         AtomicInteger synObj = new AtomicInteger(0);    40.         Print a = new Print(10,synObj,"A",0);    41.         Print b = new Print(10,synObj,"B",1);    42.         Print c = new Print(10,synObj,"C",2);    43.         a.start();    44.         b.start();    45.         c.start();    46.     }    47. }  

聯繫我們

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