gpt4 book ai didi

java - 如何在不使用 stop 方法的情况下停止线程?

转载 作者:太空宇宙 更新时间:2023-11-04 06:40:55 27 4
gpt4 key购买 nike

在下面的Java程序中,我在HashMap中存储3个线程,我创建了Th类的3个对象,它们是从Thread类扩展的(我已经尝试通过实现Runnable但它也不起作用!),我想通过分配空值在3秒后停止t2我无法停止它,我不想使用stop()方法,因为它已被弃用,它仅在我使用start方法启动线程时才有效,而如果我启动它则不起作用使用ExecutorService的execute方法的线程

public class TestingThreads {

static HashMap<String, Thread> trds = new HashMap<>();

static Th t1 = new Th("Th1");
static Th t2 = new Th("Th2");
static Th t3 = new Th("Th3");

public TestingThreads() {

}

public static void main(String[] args) {
long ct = System.currentTimeMillis();

ExecutorService executor = Executors.newCachedThreadPool();

trds.put("t1", t1);
trds.put("t2", t2);
trds.put("t3", t3);
executor.execute(t1);
executor.execute(t2);
executor.execute(t3);
executor.shutdown();
new Thread() {

@Override
public void run() {
while (true) {
if (ct + 3000 < System.currentTimeMillis()) {
trds.put("t2", null);
trds.remove("t2");
System.out.println("Size = " + trds.size());
//I dont wanna use the stop() method as is it deprecated and it only works when I use start method to run the Thread while it is not working with execute() method of class ExecutorService
// t2.stop();
t2 = null;
break;
}
}
}

}.start();
}
}

class Th extends Thread {

String name;
Random rm = new Random();

public Th(String name) {
this.name = name;
}

@Override
public void run() {
while (!this.isInterrupted()) {
int i = rm.nextInt(500);
try {
Thread.sleep(i);
} catch (InterruptedException ex) {
}
System.out.println(name + " " + i);
}
}
}

最佳答案

这只是一个线程的示例..创建一个静态 volatile boolean 标志。

static volatile boolean RUN_THREAD_FLAG= true;
Thread yourThread= new Thread(){
@Override
public void run() {
try{
// you can add your other conditions inside while condition
// and AND it with the FLAG
//while(RUN_THREAD_FLAG && yourCondition)
while(RUN_THREAD_FLAG){
sleep(SLEEP_TIME); //OR your task
}
} catch(Exception e){
e.printStackTrace();
}
}
};
yourThread.start();

当你想停止线程时,只需设置RUN_THREAD_FLAG= false

PS:您应该始终使用某些 FLAG 或其他方法尽可能长时间地正确结束线程。尽可能不要使用任何中断方法。

关于java - 如何在不使用 stop 方法的情况下停止线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24689785/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com