简体   繁体   中英

How to restart thread without using Thread.stop()?

I have a client-server application that runs the receive method to run in a separate thread. Thread is given some time to finish the job and the thread will be checked for the status.

There are occasions when the receive method will be blocked due to packet or ACK loss. If that happens, how can I stop the thread and start it again the next attempt?

As we all know, Thread.stop() is deprecated.

You can't restart a Java thread at all, with or without Thread.stop().

You have to create a new one.

You can however reuse a Runnable.

You can use interrupts to send to the thread and handle them to do a retry. Here is a sample that will start a thread that will not quit until the boolean done is set. However i'm interrupting the thread from a main thread to make it start over.

public class Runner implements Runnable {

    private boolean done;

    @Override
    public void run() {
        while (!done) {
            try {
                doSomeLongRunningStuff();

            } catch (InterruptedException e) {
                System.out.println("Interrupted..");
            }
        }
    }

    private void doSomeLongRunningStuff() throws InterruptedException {
        System.out.println("Starting ... ");
        Thread.sleep(300);
        System.out.println("Still going ... ");
        Thread.sleep(300);
        done = true;
        System.out.println("Done");
    }

    public static void main(final String[] args) throws InterruptedException {
        final Thread t = new Thread(new Runner());
        t.start();
        Thread.sleep(500);
        t.interrupt();
        Thread.sleep(500);
        t.interrupt();
    }
}

Whether you can do it this way or not depends on what you are calling. Your framework doing the TCP connection may or may not support interrupting.

一旦线程完成执行,我们不应该重新启动无效的线程。

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