java 线程池 中断_如何中断(interrupt)线程(thread)(线程池的线程中断我的理解是一个意思)...
1.概述基本實現是,通過 InterruptedException 異常來終止程序,至于線程什么時候終止,只能由jvm來決定了,若理解的不到位,歡迎大牛們指點
2.code 如下
package com.qimh.springbootfiledemo.Thread;
import com.google.common.collect.Maps;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
/**
* 演示:現在在sleep,wait,join 時 ,調用調用線程的interrupt()方法,通過異常來終止方法
* 參考連接:https://blog.csdn.net/ywl470812087/article/details/88412255
*/
public class SleepInterruptUpgrade {
static Map threads = Maps.newHashMap();
public static void main(String[] args) {
SleepThread2 t1 = new SleepThread2();
t1.start();
try {
Thread.sleep(5000);//主線程休眠
System.out.println("main thread 休眠結束....");
} catch (InterruptedException e) {
e.printStackTrace();
}
//t1.interrupt();//主動打斷線程,使SleepThread線程拋出異常
threads.get(t1.getId()).interrupt();
System.out.println("集合元素移除前個數:"+ threads.size());
//線程從map中移除
threads.remove(t1.getId());
System.out.println("集合元素移除后個數:"+ threads.size());
}
}
class SleepThread2 extends Thread {
// public synchronized void run() {
public void run() {
//線程放入map中
// SleepInterruptUpgrade.threads.put(this.getId(), this);
SleepInterruptUpgrade.threads.put(Thread.currentThread().getId(), Thread.currentThread());
while (true) {
try {
SimpleDateFormat sim = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
System.out.println(sim.format(new Date()));
sleep(1000);
// wait();
} catch (Exception e) {
e.printStackTrace();
System.out.println("線程中斷");
return;
}
}
}
}
參考連接:https://blog.csdn.net/ywl470812087/article/details/88412255
總結
以上是生活随笔為你收集整理的java 线程池 中断_如何中断(interrupt)线程(thread)(线程池的线程中断我的理解是一个意思)...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java线程 教程_Java多线程系列教
- 下一篇: java case when用法_关于o