线程停止
-
让线程正常停止 利用循环不能死循环
-
使用标志位 设置标志位
-
不用stop函数和destroy
1 public class TestStop implements Runnable{ 2 3 //1. 设置一个标志位 4 private boolean flag = true; 5 @Override 6 public void run() { 7 int i = 0; 8 while (flag){ 9 System.out.println("run....thread "+i++); 10 } 11 } 12 //2. 设置一个公开的方法停止线程,转换标志位 13 public void stop(){ 14 this.flag=false; 15 } 16 17 public static void main(String[] args) { 18 TestStop testStop = new TestStop(); 19 new Thread(testStop).start(); 20 for (int i = 0; i < 1000; i++) { 21 if(i==900){ 22 //调用stop方法切换标志位,让线程停止 23 testStop.stop(); 24 } 25 } 26 } 27 }
线程休眠
-
模拟网络时延
1 //模拟网络延迟 2 public class TestSleep implements Runnable{ 3 //票数 4 private int ticketNums =10; 5 @Override 6 public void run() { 7 8 while (true){ 9 if (ticketNums<=0){ 10 break; 11 } 12 //模拟延时 13 try { 14 Thread.sleep(200); 15 } catch (InterruptedException e) { 16 e.printStackTrace(); 17 } 18 System.out.println(Thread.currentThread().getName()+"-->拿到了第"+ticketNums--+"张票"); 19 } 20 } 21 22 public static void main(String[] args) { 23 TestSleep ticket = new TestSleep(); 24 new Thread(ticket,"gugu").start(); 25 new Thread(ticket,"zizi").start(); 26 new Thread(ticket,"haohao").start(); 27 28 } 29 }
-
模拟倒计时
1 // 模拟倒计时 2 public class TestSleep2 { 3 public static void main(String[] args) { 4 5 try { 6 tens(); 7 } catch (InterruptedException e) { 8 e.printStackTrace(); 9 } 10 //打印当前系统时间 11 Date startTime = new Date(System.currentTimeMillis());//获取系统当前时间 12 while(true){ 13 try { 14 Thread.sleep(1000); 15 System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime)); 16 startTime = new Date(System.currentTimeMillis());//更新时间 17 } catch (InterruptedException e) { 18 e.printStackTrace(); 19 } 20 21 } 22 23 } 24 public static void tens() throws InterruptedException { 25 int num =10; 26 while (true){ 27 Thread.sleep(1000); 28 System.out.println(num--); 29 if (num<=0){ 30 break; 31 } 32 } 33 } 34 }
标签:Thread,void,day21,System,休眠,线程,new,public From: https://www.cnblogs.com/GUGUZIZI/p/16830464.html