简体   繁体   中英

Start/Stop Thread Java

I'd like to start/stop a thread when I click a button.

Here is what I tried to do.

Thread thread;
String c = classMain.classes.get(a);
Class c1 = Class.forName(c);
Method ref = c1.getMethod("ref");

Object rex = c1.newInstance();
thread = new Thread(new Runnable() {
    public void run() {
        try {   
            running = true;
            ref.invoke(rex, null);
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
});
if (isRunning() == true) {
    System.out.println("Here");
    running = false;
    thread.interrupt();
    thread.join();
} else {
    thread.start();
}

For some reason interrupt() and join() don't stop the thread.

What should I do? Am I missing something?

EDIT

Alright, so I found a quick and dirty solution for this: throw a custom exception.

I'll explain better:

Instead of thread.interrupt() and thread.join() , I launch a reflected method called interrupt .

It launches an exception, that makes the Thread collapse, thus instant termination.

I am not sure whether this is efficient or not (I have to say that the method I call is a test made with Selenium, and theoretically, it should not waste resources when closed like this), so if you know more let me know.

You might want to read up on what join and interrupt do.

join just wait's for the thread to finish, interrupt just sends the interrupt signal to the thread, which normally does nothing, it will only work if the thread is waiting for some IO or similar. The interrupt signal is normally used to shut down a thread, but it is entirely up the the thread to check for it and shut down properly if it is received. Your question does not give enough detail about what is going on in your second thread to tell if this should work.

If you for some reason cannot change the code run in the thread to make it listen to interrupt you can use Thread.stop instead. It is however deprecated since using it can be dangerous since it is prone to causing deadlocks. The Javadoc for Thread links to several excellent resources on the subject.

Also note that it is illegal to start a thread more than once, which seems like what you are trying to do. You will instead need to recreate it. (as in calling new Thread and start again.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM