简体   繁体   English

如何在不使用 Thread.stop() 的情况下重新启动线程?

[英]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.有时会因为数据包或 ACK 丢失而阻塞接收方法。 If that happens, how can I stop the thread and start it again the next attempt?如果发生这种情况,我如何停止线程并在下次尝试时再次启动它?

As we all know, Thread.stop() is deprecated.众所周知,Thread.stop() 已被弃用。

You can't restart a Java thread at all, with or without Thread.stop().无论是否使用Thread.stop(). ,您都无法重新启动 Java 线程Thread.stop().

You have to create a new one.你必须创建一个新的。

You can however reuse a Runnable.但是,您可以重用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.这是一个示例,它将启动一个线程,该线程在设置布尔值 done 之前不会退出。 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.执行 TCP 连接的框架可能支持也可能不支持中断。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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