Why java doesn't support restarting a thread [duplicate]

眉间皱痕 提交于 2019-12-24 10:26:46

问题


Possible Duplicate:
How to start/stop/restart a thread in Java?

1.If you call start() on a running thread it's an error 2.If you call start() on a stopped thread nothing happens.

What's the reasoning behind not supporting restarts over the same object?


回答1:


I think the designers did it because OS-level threads usually behave in this way - they are created, they may run, then they are destroyed and the operating system performs cleanup. So probably Java designers wanted the thread notion in Java to be close to what a thread is in most operating systems. The methods start() and stop() are not meant to pause the thread (we have synchronization for that), only for letting it run and destroying the object. Maybe the names are a bit confusing. Note that stop() is deprecated and should not be used, so if we eliminate stop(), the name start() is not as confusing any more.




回答2:


Becouse of the idea behind Thread.run() method. The idea is that every thread has lifecycle and if it expires(finish the run() method block) the thread becomes dead. If you want to to stop thread for a partition of time and then run it again common way is to implement Runnable interface(or extend Thread class) and got a boolean flag inside. Here is a simple code :

public class MyThread implements Runnable {
    private Thread t;
    private boolean isRestarted;
    private boolean isInterrupted;

    public MyThread() {
           t = new Thread(this);
           isInterrupted = false;
           isRestarted = false;
           t.start();
    }

    public void run() {
       //Do somework
       while(true) {
         if(isInterrupted) break;
         if(isRestarted) run();
       }
    }

    public void restart() { isRestarted = true; }
    public void interupt() { isInterrupted = true; }
 }

Now when the thread isn't interupted it will wait to be restarted. When you interupt it it can't be restarted any more .



来源:https://stackoverflow.com/questions/10042457/why-java-doesnt-support-restarting-a-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!