11.4-全棧Java筆記:線程三種狀態的控制
關於Java線程終止、暫停、聯合的文章網上有很多,經過測試,本節重點講解的是針對不同使用場景選擇合適的方法。
終止線程的典型方式
終止線程我們一般不使用JDK提供的stop()/destroy()方法(他們本身也被JDK廢棄了)。通常的做法是提供一個boolean型的終止變量,當這個變量置為false,則終止線程的運行。
【示例1】終止線程的典型方法(重要!!!)
public class TestThreadCiycle implements Runnable { String name; boolean live = true; public TestThreadCiycle(String name) { super(); this.name = name; }
public void run() { int i=0; while(live){ System.out.println(name+(i++)); } } public void terminate(){ live = false; }
public static void main(String[] args) { TestThreadCiycle ttc = new TestThreadCiycle(" Thread t1 = new Thread(ttc); //新生狀態 t1.start(); //就緒狀態 for(int i=0;i<1000;i++){ System.out.println(i); } ttc.terminate(); System.out.println("ttc stop!"); }
} |
暫停線程執行sleep/yield
sleep()可以讓正在運行的線程進入阻塞狀態,直到休眠時間滿了,進入就緒狀態。yield()可以讓正在運行的線程直接進入就緒狀態,讓出
【示例2】暫停Threads的方法sleep、yield
public class TestThreadState { public static void main(String[] args) { //使用繼承方式實現多線程 StateThread thread1 = new StateThread(); thread1.start(); StateThread thread2 = new StateThread(); thread2.start(); } }
class StateThread extends Thread { public void run(){ for(int i=0;i<100;i++){ System.out.println(this.getName()+":"+i); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } //Thread.yield(); } } }
|
線程的聯合join()
線程A在運行期間,可以調用線程B的join()方法,讓線程B和線程A聯合。這樣,線程A就必須等待線程B執行完畢後,才能繼續執行。
如下面示例中,“爸爸線程”要抽煙,於是聯合了“兒子線程”去買煙,必須等待“兒子線程”買煙完畢,“爸爸線程”才能繼續抽煙。
【示例3】測試線程的聯合join()方法
public class TestThreadState { public static void main(String[] args) { System.out.println("爸爸和兒子買煙故事"); Thread father = new Thread(new FatherThread()); father.start(); } }
class FatherThread implements Runnable { public void run() { System.out.println("爸爸想抽煙,發現煙抽完了"); System.out.println("爸爸讓兒子去買包紅塔山"); Thread son = new Thread(new SonThread()); son.start(); System.out.println("爸爸等兒子買煙回來"); try { son.join(); } catch (InterruptedException e) { e.printStackTrace(); System.out.println("爸爸出門去找兒子跑哪去了"); System.exit(1);//結束JVM。如果是0則表示正常結束;如果是非0則表示非正常結束 } System.out.println("爸爸高興的接過煙開始抽,並把零錢給了兒子"); } } class SonThread implements Runnable { public void run() { System.out.println("兒子出門去買煙"); System.out.println("兒子買煙需要10分鐘"); try { for (int i = 1; i <=10;i++) { System.out.println("第" + i + "分鐘"); Thread.sleep(1000); } } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("兒子買煙回來了"); } } |
「全棧Java筆記」是一部能幫大家從零到一成長為全棧Java工程師系列筆記。筆者江湖人稱 Mr. G,10年Java研發經驗,曾在神州數碼、航天院某所研發中心從事軟件設計及研發工作,從小白逐漸做到工程師、高級工程師、架構師。精通Java平臺軟件開發,精通JAVAEE,熟悉各種流行開發框架。
筆記包含從淺入深的六大部分:
A-Java入門階段
B-數據庫從入門到精通
C-手刃移動前端和Web前端
D-J2EE從了解到實戰
E-Java高級框架精解
F-Linux和Hadoop
本文出自 “12931675” 博客,請務必保留此出處http://12941675.blog.51cto.com/12931675/1945760
11.4-全棧Java筆記:線程三種狀態的控制