Reputation: 233
I would like to make that OptionPanel makes threads shutdown themselves. I know it suppose to be done in the run method of the thread class but I don't know if I should to synchronize something there or not.
How to make that these threads will shut themselves after clicking correct option in 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;
}
}
}
}
Upvotes: 0
Views: 123
Reputation: 272217
Given that you have:
Thread.sleep(interv * 100);
I would look at sending an interrupt to each thread. The interrupt will do just that to the sleep()
method and it will be more responsive than the usual practise of looping around a boolean (e.g. while (!done) {....}
).
As well as the tutorial linked above, check out this DeveloperWorks article on handling InteruptedExceptions.
Upvotes: 2