错误的停止线程

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 @   创嗨  阅读(52)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示