gpt4 book ai didi

java - 我是否正确关闭了这些并发线程

转载 作者:行者123 更新时间:2023-12-01 20:06:09 26 4
gpt4 key购买 nike

如主题所示,我是否正确关闭这些并发线程?

我分配了一个 volatile 字段并在 while 循环中重复检查它。

是否有替代方法(例如使用同步或 wait() 方法),请告诉我。

编辑我编辑了代码。有没有什么方法可以通过 isAlive(); 不同的方法来检查线程是否还活着?也许:

boolean isAlive(){
return running;
}
<小时/>
import javax.swing.JOptionPane;

public class Wat extends Thread {
private char c;
private int interv;
private volatile boolean running = true;
Object synchObj;

public Wat(char c, int interv) {
this.c = c;
this.interv = interv;
synchObj = new Object();
}

public void run() {
while (running) {
synchronized (synchObj) {
try {
showChar(c);
synchObj.wait(interv * 100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

}

public synchronized static void showChar(char c) {
System.out.println(c);
}

public void shutdown() {
running = false;
synchronized (synchObj) {
synchObj.notify();
}
}

public static void main(String[] args) throws InterruptedException {
Wat w1 = new Wat('A', 3);
Wat w2 = new Wat('B', 4);
Wat w3 = new Wat('C', 5);
w1.start();
w2.start();
w3.start();
Object[] options = { "Shutdown A", "Shutdown B", "Shutdown C" };
int option;
while (w1.isAlive() || w2.isAlive() || w3.isAlive()) {
option = JOptionPane.showOptionDialog(null,
"Which one would you like to shut?", "Threads",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE, null, options, options[2]);
switch (option) {
case JOptionPane.YES_OPTION:
w1.shutdown();
break;
case JOptionPane.NO_OPTION:
w2.shutdown();
break;
case JOptionPane.CANCEL_OPTION:
w3.shutdown();
break;
}
Thread.sleep(1);
}
}
}

最佳答案

您的代码可能会正常工作,但 Thread.sleep 不是很优雅。我会按照这些思路做一些事情,调用 shutdown() 方法来退出线程

 Object synchObj = new Object();

public void run() {
while (running) {
synchronized (synchObj) {
try {
System.out.println(new Date());
synchObj.wait(5000);
} catch (InterruptedException e) {
// error handling
}
}
}
}

public void shutdown() {
running = false;
synchronized (synchObj) {
synchObj.notify();
}
}


public static void main(String[] args) throws InterruptedException,
IOException {
ThreadTest test = new ThreadTest();
test.start();
BufferedReader tReader = new BufferedReader(new InputStreamReader(
System.in));
tReader.readLine();
test.shutdown();
}

编辑添加测试代码

关于java - 我是否正确关闭了这些并发线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13247859/

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