JavaSE-20.1.4【线程控制(sleep、join、daemon)】
1 package day11.lesson1.p4; 2 3 /* 4 1.5 线程控制 5 6 static void sleep(long millis) 使当前正在执行的线程停留(暂停执行)指定的毫秒数 7 void join() 等待这个线程死亡 8 void setDaemon(boolean on) 将此线程标记为守护线程,当运行的线程都是守护线程时,Java虚拟机将退出 9 10 */ 11 public class ThreadSleep extends Thread{ 12 @Override 13 public void run() { 14 for (int i=0; i<20; i++){ 15 System.out.println(getName() + ":" + i); 16 17 try { 18 Thread.sleep(1000); // 19 } catch (InterruptedException e) { 20 e.printStackTrace(); 21 } 22 } 23 } 24 } 25 26 class ThreadSleepDemo{ 27 public static void main(String[] args) { 28 ThreadSleep ts1 = new ThreadSleep(); 29 ThreadSleep ts2 = new ThreadSleep(); 30 ThreadSleep ts3 = new ThreadSleep(); 31 32 ts1.setName("曹操"); 33 ts2.setName("刘备"); 34 ts3.setName("孙权"); 35 36 ts1.start(); 37 ts2.start(); 38 ts3.start(); 39 /* 40 设置sleep()之前输出:三者混杂且随机 41 设置sleep()之后输出:三者均衡 42 曹操:0 43 孙权:0 44 刘备:0 45 曹操:1 46 孙权:1 47 刘备:1 48 曹操:2 49 刘备:2 50 孙权:2 51 刘备:3 52 孙权:3 53 曹操:3 54 孙权:4 55 曹操:4 56 刘备:4 57 */ 58 } 59 }
1 package day11.lesson1.p4; 2 3 /* 4 void join() 等待这个线程死亡 5 例:两位皇子争夺皇位,需等待老皇帝驾崩 6 */ 7 public class ThreadJoin extends Thread{ 8 @Override 9 public void run() { 10 for (int i=0; i<20; i++){ 11 System.out.println(getName() + ":" + i); 12 } 13 } 14 } 15 16 class ThreadJoinDemo{ 17 public static void main(String[] args) { 18 ThreadJoin tj1 = new ThreadJoin(); 19 ThreadJoin tj2 = new ThreadJoin(); 20 ThreadJoin tj3 = new ThreadJoin(); 21 22 tj1.setName("老皇帝"); 23 tj2.setName("皇子1号"); 24 tj3.setName("皇子2号"); 25 26 tj1.start(); 27 try { 28 tj1.join(); //tj1线程执行完毕后,tj2和tj3线程才能执行 29 } catch (InterruptedException e) { 30 e.printStackTrace(); 31 } 32 33 tj2.start(); 34 tj3.start(); 35 } 36 }
1 package day11.lesson1.p4; 2 3 /* 4 void setDaemon(boolean on) 将此线程标记为守护线程,当运行的线程都是守护线程时,Java虚拟机将退出 5 例:桃园三结义不求同年同月同日生,但求同年同月同日死,假如刘备没了,则关张也不再苟活 6 */ 7 public class ThreadDaemon extends Thread{ 8 @Override 9 public void run() { 10 for (int i=0; i<100; i++){ 11 System.out.println(getName() + ":" + i); 12 } 13 } 14 } 15 16 class ThreadDaemonDemo{ 17 public static void main(String[] args) { 18 ThreadDaemon td1 = new ThreadDaemon(); 19 ThreadDaemon td2 = new ThreadDaemon(); 20 21 td1.setName("关羽"); 22 td2.setName("张飞"); 23 24 //设置主线程为刘备 25 Thread.currentThread().setName("刘备"); 26 //设置守护线程 27 td1.setDaemon(true); 28 td2.setDaemon(true); 29 30 td1.start(); 31 td2.start(); 32 33 for (int i=0; i<10; i++){ 34 System.out.println(Thread.currentThread().getName() + ":" + i); 35 } 36 } 37 }