나는 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