如何正确关闭这些线程

时间:2012-11-05 17:50:34

标签: java multithreading

我想让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;
            }
        }

    }

}

1 个答案:

答案 0 :(得分:2)

鉴于你有:

Thread.sleep(interv * 100);

我会考虑向每个帖子发送一个interrupt。中断将对sleep()方法执行此操作,并且它比循环布尔值的常规做法(例如while (!done) {....})更具响应性。

除了上面链接的教程之外,请查看关于handling InteruptedExceptions的这篇DeveloperWorks文章。