0

我正在实现一个程序,它将 rtp 音频传输到对等计算机,同时运行一个线程来获取 ping 数据。单击开始按钮后,两种方法几乎同时启动。问题是当我想中断/退出程序时,ping 数据不会显示输出,但线程仍在运行。

开始按钮

JButton startCap = new JButton("Start");
    startCap.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent act) {

                            go();//go() is the rtp audio method

                        Thread pinging = new Thread() {
                            public void run() {

                                PingTest();
                            }
                        };

                        pinging.setName("runPing");
                        pinging.start();

        }
    });

退出按钮

JButton stopCap = new JButton("Exit");
    stopCap.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent act) {
                            //just for some checking, I know its not a good design
                            //I new at here
            if (sink != null) {
                sink.addDataSinkListener(new DataSinkListener() {
                    public void dataSinkUpdate(DataSinkEvent e) {
                        if(e instanceof EndOfStreamEvent)
                            sink.close();
                    }
                });
            }
            if (processor != null)
                processor.stop();
                            System.exit(-1);
                            //I think there no need to return, but still put at there
                            Thread.currentThread().interrupt();//preserve the message
                            pinging.currentThread().interrupt();
                            return;//
                            //Runtime.getRuntime().halt(0);
                            //pinging.stop();
                            }

    });

一些 GUI 代码

public static void createAndShowGui() {
    JFrame frame = new JFrame("Sender");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(new SimpleVoiceTransmiter());
    frame.setSize(200, 75);
    frame.setVisible(true);
    frame.toFront();
}

public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGui();
        }
    });
}

go() 是主要方法,而 PingTest() 是依赖方法,当 go() 通过单击“开始”按钮启动时,PingTest() 将启动。现在的问题是我不知道如何中断/退出 PingTest()。如何同时中断/退出所有线程(PingTest())?真的需要一些提示,在此先感谢。

p/s:PingTest() 正在使用 Runtime.exec() 来 ping 对等计算机。

4

1 回答 1

1

pinging.currentThread()不返回 ping 线程。它等价于Thread.currentThread(), 因为currentThread()是一个静态方法。要获取 pinging 线程,只需使用pinging

pinging.interrupt();

我也不明白你为什么要中断当前线程。当前线程是事件调度线程,它正在运行您的 GUI。没有理由打断它。

于 2013-03-03T09:24:10.070 回答