如果我们想在一个线程中终止另一个线程我们一般不使用 JDK 提供的 stop()/destroy() 方法(它们本身也被 JDK 废弃了)。通常的做法是提供一个 boolean 型的终止变量,当这个 变量值为 false 时
如果我们想在一个线程中终止另一个线程我们一般不使用 JDK 提供的 stop()/destroy() 方法(它们本身也被 JDK 废弃了)。通常的做法是提供一个 boolean 型的终止变量,当这个 变量值为 false 时,则终止线程的运行
package com.yqq.app12;import java.io.IOException;
/**
* @Author yqq
* @Date 2021/11/24 01:23
* @Version 1.0
*/
public class StopThread implements Runnable{
private boolean flag = true;
public void run() {
System.out.println(Thread.currentThread().getName()+"线程开始");
int i = 0;
while (flag){
System.out.println(Thread.currentThread().getName()+" "+i++);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"线程结束");
}
public void stop(){
this.flag = false;
}
public static void main(String[] args) throws IOException {
System.out.println("主线程开始");
StopThread st = new StopThread();
Thread t1 = new Thread(st);
t1.start();
System.in.read();
st.stop();
System.out.println("主线程结束");
}
}主线程开始
Thread-0线程开始
Thread-0 0
Thread-0 1
Thread-0 2
Thread-0 3
Thread-0 4
Thread-0 5
o
主线程结束
Thread-0线程结束