Reputation: 33
I have a separate class implementing runnable, but whenever I start the thread, I cannot press the stop button on the GUI. I'm not sure whether I am doing things correctly as I have never done multithreading before in Java project of this scale. I'm already far into the project, and I hadn't tested the stop thread function until now.
I looked into implementing things like this, but I wasn't sure how: https://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html
These are the bits of code to start and stop the thread
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);
}
});
This is what my class which is being initialized in the other thread looks like
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
}
}
}
}
you can also see where I write "//there were about 1000 lines here that I deleted in which I start 2 other threads." The classes which are initialized are mostly similar to the BotFunc class and I was wondering how I could interrupt these threads as well.
Upvotes: 1
Views: 240
Reputation: 11020
I think the problem is calling run()
from the constructor of BotFunc
:
public BotFunc(String token,String proxies,String sID,String msgC) {
token1=token;proxies1=proxies;sID1=sID;msgC1=msgC;
run(); // <---- DON'T DO THIS!!
}
Calling run()
like this will execute the code body on the main GUI thread, causing the GUI to block. Don't do this.
Just to explain a bit more, Thread.start()
calls run()
for you, there's no need for you to do it.
/* Fake Thread implementation */
public class Thread {
public void start() {
/* starts a new thread, then... */
run(); // just calls run()
}
}
Calling run()
from the ctor causes the GUI thread to run the body of your Runnable
, because it's the GUI thread that calls the ctor, and the body of the ctor is just executing on the GUI thread as a result.
Upvotes: 2