java 線程理解

來源:互聯網
上載者:User

標籤:重寫   介面   java 線程   throws   擷取   代碼   exception   喚醒   alt   

線程建立有兩種方式: 1、實現runnable介面  2、繼承thread 線程   都重寫run方法 2、runnable介面優勢:        java 單繼承但可以實現多個介面        runnable 方式可以實現多線程共用一個公用資源 3、線程的生命週期:見

 

4、那麼sleep 和 wait 是什嗎?      用於暫停線程使其他線程擷取CUP時間片進行執行   5、各自區別:      sleep 是 thread 的方法   意義:等待多少毫秒後再喚醒且不會釋放對象鎖      wait 是object 方法 需要通過notify 或者 notifyAll 進行喚醒  意義:將該線程掛起釋放對象鎖
 //以下類比3個視窗同時售賣5張車票的線程代碼。 //可以說明runnable 介面優勢中多線程共用一個公用資源private int titickits =500000;          public static void main(String[] args) throws InterruptedException {           Titickits t=new Titickits();                      Thread t1=new Thread(t,"視窗A");           Thread t2=new Thread(t,"視窗B");           Thread t3=new Thread(t,"視窗C");                      t1.start();           t2.start();           t3.start();           t1.wait();     }     public  void run() {           while(titickits>0) {                titickits--;                System.out.println(Thread.currentThread().getName()+"剩餘"+titickits);           }     }

 

java 線程理解

聯繫我們

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