错误的停止线程

1.使用stop()方法错误的停止线程,会导致强行停止,而不给考虑的机会,interrupt不会直接停止

import lombok.extern.slf4j.Slf4j;

@Slf4j
/**
* 使用stop()方法错误的停止线程,会导致强行停止,而不给考虑的机会,interrupt不会直接停止
*/
public class StopThread implements Runnable{
@Override
public void run() {
for (int i=1;i<=5;i++){
log.info("第"+i+"支军队获取材料");
for (int j=1;j<=10;j++){
log.info("第"+i+"支军队领了"+j);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println("_________________________________");
log.error("我"+e.getMessage());
}
}

}
}
public void threadSleep() throws InterruptedException {
Thread.sleep(670);
}

public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new StopThread());
thread.start();
Thread.sleep(10);
thread.start();
}
}

2.演示volatile的局限性,看似可行的停止

/**
* 演示volatile的局限性,看似可行的停止
*/
public class WrongWayVolatile implements Runnable{
private volatile Boolean volatileBool=false;
@Override
public void run() {
int num = 0;
try {
while (!volatileBool && num<=10000){

if(num%100==0){
System.out.println(num+"是100的倍数");
}
num++;
Thread.sleep(1);
}
}catch (Exception e){
e.printStackTrace();
}
}

public static void main(String[] args) throws InterruptedException {
WrongWayVolatile wrongWayVolatile = new WrongWayVolatile();
Thread thread = new Thread(wrongWayVolatile);
thread.start();
Thread.sleep(500);
wrongWayVolatile.volatileBool = true;
}
}
posted @ 2021-11-05 09:24  创嗨  阅读(44)  评论(0编辑  收藏  举报