我有一个单独的类,该类实现可运行的,但是无论何时启动线程,都无法按GUI上的“停止”按钮。我不确定我是否做正确的事,因为我以前从未在这种规模的Java项目中做过多线程处理。我已经很了解这个项目,并且直到现在我还没有测试过停止线程功能。
我研究了实现这样的事情,但不确定如何:https://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html
这些是启动和停止线程的代码位
Runnable r;
Thread t1;
String token,proxies,sID,msgC;
JButton btnNewButton_1 = new JButton("Start Thread");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
token=txtEnterBotToken.getText();
proxies=textArea.getText();
sID=txtEnterServerId.getText();
msgC=textField_1.getText();
r=null;
t1=new Thread(r);
r = new BotFunc(token,proxies,sID,msgC);
if(!t1.isAlive())t1.start();
}
});
JButton btnNewButton_2 = new JButton("Stop Thread");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
t1.interrupt();
t1=new Thread(r);
}
});
这是我在另一个线程中初始化的类的样子public class BotFunc implements Runnable {
private String token1,proxies1,sID1,msgC1;
public BotFunc(String token,String proxies,String sID,String msgC) {
token1=token;proxies1=proxies;sID1=sID;msgC1=msgC;
run();
}
public void run()
{
{
{
System.out.println("t1 running");
//there were about 1000 lines here that I deleted in which I start 2 other threads
}
}
}
}
您还可以看到我写的位置“//这里删除了大约1000行,并在其中开始了另外2个线程。”初始化的类与BotFunc类非常相似,我想知道如何也可以中断这些线程。
最佳答案
我认为问题是从run()
的构造函数调用BotFunc
:
public BotFunc(String token,String proxies,String sID,String msgC) {
token1=token;proxies1=proxies;sID1=sID;msgC1=msgC;
run(); // <---- DON'T DO THIS!!
}
像这样调用run()
将在主GUI线程上执行代码主体,从而导致GUI阻塞。不要这样为了进一步说明,
Thread.start()
为您调用run()
,您无需这样做。/* Fake Thread implementation */
public class Thread {
public void start() {
/* starts a new thread, then... */
run(); // just calls run()
}
}
从ctor调用run()
会导致GUI线程运行Runnable
的主体,因为是GUI线程调用了ctor,因此ctor的主体只是在GUI线程上执行。
关于java - 如何使用2个按钮使多线程swing GUI应用程序启动/停止线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66715657/