关于java 线程的停止同时用 interrupt 和 join 的作用

 

/**

 * @FileName: ThreadTest.java

 * @Description:

 * @Author : xingchong

 * @CreateTime: Sep 22, 2018 12:01:01 PM

 * @Copyright: 超火影游 Copyright (c) 2017

 * @Version: 1.0

 */

public class ThreadTest implements Runnable {

 

private boolean stop = false;

 

private Thread thread;

 

private int flag;

 

public ThreadTest(){

this.thread = new Thread(this, ThreadTest.class.getSimpleName());

this.flag = 0;

}

 

private String getName(){

return "["+Thread.currentThread().getName()+"] ";

}

 

/*

* (non-Javadoc)

* 

* @see java.lang.Runnable#run()

*/

@Override

public void run() {

while(!stop){

System.out.println(this.getName() +", i am running..."+ this.flag++);

if(this.flag > 30){

break;

}

try {

Thread.sleep(2000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

System.out.println(this.getName()+", i am end...");

}

 

public synchronized void start(){

this.thread.start();

}

 

public synchronized void stop(){

System.out.println(this.getName() +", stop the thread...");

this.stop = true;

this.thread.interrupt();//马上中断 thread 正在进行的 sleep 等操作,而让停止操作立即执行

//若没有上面interrupt()方法,会导致 thread 发呆在 sleep ,担耽时机

 

try {

this.thread.join();//为了现在马上转入 thread 线程,以触发this.stop引起的停止操作,而不用再让main线程抢 CPU,担耽时机

} catch (InterruptedException e) {

e.printStackTrace();

}

 

//若没有上面的 join()方法,会导致以下代码在停止前执行

for (int i = 0; i < 3; i++) {

System.out.println(this.getName() +"in stop ...");

}

}

 

public static void main(String[] args) {

ThreadTest threadTest = new ThreadTest();

threadTest.start();

 

for (int i = 0; i < 3; i++) {

System.out.println(threadTest.getName()+", main...." + i);

try {

Thread.sleep(2000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

 

threadTest.stop();

System.out.println(threadTest.getName()+", main is end...");

}

 

}

posted @   会飞的斧头  阅读(918)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示