我正在实现一个程序,它将 rtp 音频发送到对等计算机,同时运行一个线程来获取 ping 数据。一旦我单击开始按钮,两种方法几乎同时启动。问题是当我想中断/退出程序时,ping 数据不会显示输出,但线程仍在运行。
Start button
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();
}
});
Exit button
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();
}
});
Some GUI code
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())?真的需要一些提示,提前致谢。
最佳答案
pinging.currentThread()
不返回 ping 线程。它相当于 Thread.currentThread()
,因为 currentThread()
是一个静态方法。要获取 ping 线程,只需使用 pinging
:
pinging.interrupt();
我也不明白为什么你会中断当前线程。当前线程是事件调度线程,它正在运行您的 GUI。没有理由中断它。
关于java - 如何在Java中使用内联类中断线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15184192/