如何重启线程?

时间:2011-01-04 19:14:40

标签: java multithreading runnable

它是一个RMI Server对象,可能会运行很多sethumanActivity(),如何在新的changeToFalse运行之前确保先前的changeToFalse线程停止或停止? t. interrupt

基本上,当调用sethumanActivity()时,humanActivity将设置为true,但是将运行一个线程将其设置为false。但我正在考虑如何在调用另一个sethumanActivity()时禁用或终止该线程?

public class VitaminDEngine implements VitaminD {

    public boolean humanActivity = false;
    changeToFalse cf = new changeToFalse();
    Thread t = new Thread(cf);


    private class changeToFalse implements Runnable{

        @Override
        public void run() {
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            humanActivity = false;
        }

    }

    @Override
    public void sethumanActivity() throws RemoteException {
        // TODO Auto-generated method stub
        humanActivity = true;
        t.start();
    }

    public boolean gethumanActivity() throws RemoteException {
        // TODO Auto-generated method stub
        return humanActivity;
    }

}
在SOer的帮助下

编辑

package smartOfficeJava;

import java.rmi.RemoteException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class VitaminDEngine implements VitaminD {

    public volatile boolean humanActivity = false;
    changeToFalse cf = new changeToFalse();
    ExecutorService service = Executors.newSingleThreadExecutor();


    private class changeToFalse implements Runnable{

        @Override
        public void run() {
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            humanActivity = false;
        }

    }

    @Override
    public synchronized  void sethumanActivity() throws RemoteException {
        humanActivity = true;
        service.submit(cf);
    }

    public synchronized  boolean gethumanActivity() throws RemoteException {
        return humanActivity;
    }

}

2 个答案:

答案 0 :(得分:4)

使用ExecutorService。 ExecutorService将创建一个单独的线程,您可以根据需要多次提交runnable。

ExecutorService service = Executors.newSingleThreadExecutor();

然后在你的代码中

@Override
public void sethumanActivity() throws RemoteException {
    // TODO Auto-generated method stub
    humanActivity = true;
   service.submit(cf);
}

另外,为了正确起见,您不安全地写入humanActivity字段。有陈旧阅读的可能性。有许多文章讨论了可见性,您可以查看here

答案 1 :(得分:2)

Thread.interrupt()中断等待,Thread.join()在继续之前等待线程完成。

相关问题