Java多線程其他

來源:互聯網
上載者:User

標籤:size   子線程   tde   ace   lang   imp   斷線   cep   放棄   

1.interrupt()方法

  interrupt方法不會真正中斷線程,它只會清楚線程的wait,sleep,join的受阻狀態,時線程重新獲得CPU的執行權。

  此時如果再次調用線程的wait,sleep,join方法,將會拋出一個InterruptedException異常

package threadinterrupt;public class InterruptDemo {public static void main(String[] args) throws InterruptedException {Thread t = new Thread(new Runnable() {private boolean flag = true;@Overridepublic void run() {synchronized (this) {int i = 1;while(flag){System.out.println("=========" + i++ + "=========");if (i > 10) {try {System.out.println("子線程將停止執行");i =0;wait();} catch (InterruptedException e) {System.out.println("第二次調用wait()時拋出異常");e.printStackTrace();break;}}}}}});t.start();Thread.sleep(2000);t.interrupt();System.out.println("子線程將繼續執行");}}

  

2.join()方法,t1.join方法代表著當前線程放棄CPU執行資格,需要等到t1執行完畢時才能獲得CPU執行資格

package threadinterrupt;import java.lang.Thread.State;public class ThreadJoin {public static void main(String[] args) throws InterruptedException {Runnable r = new  Runnable() {@Overridepublic void run() {for (int i = 0; i < 1000; i++) {System.out.println(Thread.currentThread().getName()+":========"+i+"========");}}};Thread t1 = new Thread(r);Thread t2 = new Thread(r);t1.start();t2.start();//System.out.println("主線程需要等到t1執行完畢才會執行");//t1.join();if(t1.getState() == State.RUNNABLE){System.out.println("【沒有】t1.join()時這句話會被執行");}if(t1.getState() == State.TERMINATED){System.out.println("【有】t1.join()時這句話會被執行");}}}

  

3.yield()方法,暫停當前正在執行的線程對象,並執行其他線程,該方法不會讓該線程放棄CPU的執行權,該線程任然可以爭奪CPU執行權

package threadinterrupt;public class ThreadYield {public static void main(String[] args) {Runnable r = new Runnable() {@Overridepublic void run() {for (int i = 0; i < 1000; i++) {System.out.println(Thread.currentThread().getName()+ ":========" + i + "========");Thread.yield();}}};Thread t1 = new Thread(r);Thread t2 = new Thread(r);System.out.println("在子線程的run方法中添加Thread.yield();兩個線程將會交替(不是絕對交替)");t1.start();t2.start();}}

  

4.setDaemon(boolean on)方法,將該線程標記為守護線程或使用者線程。

5.setPriority(int newPriority) 更改線程的優先順序(1-10)數字越大,優先順序越高

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.