我想使OptionPanel自己關閉線程。我知道它假設在線程類的run方法中完成,但是我不知道是否應該同步某些內容。如何正確關閉這些線程
如何使這些線程在點擊JOptionPanel中的正確選項後自行關閉?
import javax.swing.JOptionPane;
public class Wat extends Thread {
private char c;
private int interv;
private volatile boolean running = true;
public Wat(char c, int interv) {
this.c = c;
this.interv = interv;
}
public void run() {
while (running) {
try {
System.out.println(c);
Thread.sleep(interv * 100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
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.running = false;
break;
case JOptionPane.NO_OPTION:
w2.running = false;
break;
case JOptionPane.CANCEL_OPTION:
w3.running = false;
break;
}
}
}
}
http://stackoverflow.com/questions/5562720/how-to-access-the-running-thread-runnable的部分副本。使用那裏的技術。 –
下面是關於如何中斷一個線程的信息:http://stackoverflow.com/questions/9791361/thread-not-interrupting/9791479#9791479 – Gray
我已編輯我的問題是代碼是正確的嗎?它可以做得更好嗎? – Robert