当前位置 : 主页 > 编程语言 > java >

终止线程的优选并不是stop()与destroy()

来源:互联网 收集:自由互联 发布时间:2022-07-04
如果我们想在一个线程中终止另一个线程我们一般不使用 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;
@Override
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线程结束


上一篇:sleep与yield的区别
下一篇:没有了
网友评论