java的知识点29——join:合并线程 插队线程、线程的状态
生活随笔
收集整理的這篇文章主要介紹了
java的知识点29——join:合并线程 插队线程、线程的状态
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
join:合并線程 插隊線程
?實例:?爸爸和孩子買煙的故事
/*** join:合并線程 插隊線程* 爸爸和孩子買煙的故事* @author Administrator**/
public class BlockedJoin02 {public static void main(String[] args) {System.out.println("爸爸和孩子買煙的故事");new Thread(new Father()).start();}
}
class Father extends Thread{public void run() {System.out.println("想抽煙,發現沒啦");System.out.println("讓兒子去買中華");Thread t=new Thread(new Son());t.start();try {t.join(); //father線程被阻塞System.out.println("老爸接過煙,把零錢給啦兒子");} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();System.out.println("孩子走丟啦,老爸找孩子去啦");}}
}
class Son extends Thread{public void run() {System.out.println("接過老爸的錢出去啦。。。");System.out.println("路邊有個游戲廳,玩了10秒");for(int i=1;i<=10;i++) {System.out.println(i+"秒過去啦。。。。");try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}System.out.println("趕緊買煙去");System.out.println("手拿一包中華,回家啦");}
}
線程的狀態
import java.lang.Thread.State;/*** 觀察線程的狀態* @author Administrator**/ public class AllState {public static void main(String[] args) {Thread t=new Thread(()->{for(int i=0;i<5;i++) {try {Thread.sleep(100); //TIMED_WAITING} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("....");} });//觀察狀態State state=t.getState();System.out.println(state); //NEWt.start();state=t.getState(); System.out.println(state); //RUNNABLEwhile(state!=Thread.State.TERMINATED) {try {Thread.sleep(200);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}state=t.getState(); System.out.println(state);}} }import java.lang.Thread.State;/*** 觀察線程的狀態* @author Administrator**/ public class AllState {public static void main(String[] args) {Thread t=new Thread(()->{for(int i=0;i<5;i++) {try {Thread.sleep(100); //TIMED_WAITING} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("....");} });//觀察狀態State state=t.getState();System.out.println(state); //NEWt.start();state=t.getState(); System.out.println(state); //RUNNABLEwhile(true) {int num=Thread.activeCount(); //活動的線程數System.out.println(num);if(num==1) {break;}try {Thread.sleep(200);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}state=t.getState(); System.out.println(state);} } }
總結
以上是生活随笔為你收集整理的java的知识点29——join:合并线程 插队线程、线程的状态的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java的知识点28——线程的生命周期
- 下一篇: 数据库知识点4——关系代数中易错题的总结