线程停止,休眠,礼让, 强制执行
- 建议循环正常停止,利用次数,不建议死循环
建议使用标志位–>使用标志位
不要使用stop()或者destroy等过时的jdk不建议的方法
线程停止
package com.state;
public class TestStop implements Runnable{
//设置一个标志位
private boolean flag=true;
@Override
public void run() {
int i=0;
while(flag){
System.out.println("run...Thread"+i++);
}
}
//设置一个公开的方法停止线程,转换标志位
public void stop(){
this.flag=false;
}
public static void main(String[] args) {
TestStop testStop=new TestStop();
new Thread(testStop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main"+i);
if(i==900){
//调用stop方法切换标志位
testStop.stop();
System.out.println("线程停止了");
}
}
}
}
main897
main898
main899
main900
run...Thread999
线程停止了
main901
main902
main903
main904
main905
main906
main907
线程休眠
-
模拟网络延时,放大问题的发生性。
-
模拟倒计时。
获取当前系统时间 /s
package com.state; import java.text.SimpleDateFormat; import java.util.Date; public class TestSleep { public static void main(String[] args) { //打印当前系统时间 Date startTime=new Date(System.currentTimeMillis()); while(true){ try { Thread.sleep(1000); System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime)); startTime=new Date(System.currentTimeMillis());// 更新当前时间 } catch (InterruptedException e) { e.printStackTrace(); } } } }
01:28:29 01:28:30 01:28:32 01:28:33 01:28:34 01:28:35 01:28:36 01:28:37 01:28:38 01:28:39 01:28:40 01:28:41
倒计时
package com.state;
public class TestSleep2 {
public static void main(String[] args) {
try {
tenDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void tenDown() throws InterruptedException{
int num=10;
while(true){
Thread.sleep(1000);
System.out.println(num--);
if(num<=0){
break;
}
}
}
}
10
9
8
7
6
5
4
3
2
1
线程礼让
package com.state;
//礼让是出来之后重新调度,运行顺序仍由cpu决定。
public class TestYield {
public static void main(String[] args) {
MyYield myYield=new MyYield();
new Thread(myYield,"a").start();
new Thread(myYield,"b").start();
}
}
class MyYield implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"线程开始执行");
Thread.yield();
System.out.println(Thread.currentThread().getName()+"线程停止执行");
}
}
a线程开始执行
b线程开始执行
a线程停止执行
b线程停止执行
线程强制执行
package com.state;
public class TestJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("线程vip来了");
}
}
public static void main(String[] args) throws InterruptedException {
//启动线程
TestJoin testJoin=new TestJoin();
Thread thread=new Thread(testJoin);
thread.start();
//主线程
for (int i = 0; i < 1000; i++) {
if(i==200){
thread.join();
}
System.out.println("main"+i);
}
}
}
main196
main197
main198
main199
线程vip来了
线程vip来了
线程vip来了
线程vip来了
线程vip来了
线程vip来了
线程vip来了
线程vip来了
线程vip来了
线程vip来了
线程vip来了
线程vip来了
线程vip来了
线程vip来了
线程vip来了
线程vip来了
线程vip来了
线程vip来了
线程vip来了
线程vip来了
线程vip来了
线程vip来了
线程vip来了
线程vip来了