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——线程的生命周期
- 下一篇: 计算机网络知识点1——计算机网络概述