how to restart a Thread?

Posted by wizztjh on Stack Overflow See other posts from Stack Overflow or by wizztjh
Published on 2011-01-04T19:14:39Z Indexed on 2011/01/05 3:54 UTC
Read the original article Hit count: 271

Filed under:
|
|

It is a RMI Server object , so many sethumanActivity() might be run , how do i make sure the previous changeToFalse thread will be stop or halt before the new changeToFalse run? t. interrupt ?

Basically when sethumanActivity() is invoke , the humanActivity will be set to true , but a thread will be run to set it back to false. But I am thinking for how to disable or kill the thread when another sethumanActivity() invoked?

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;
    }

}

Edited after the help of 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;
    }

}

© Stack Overflow or respective owner

Related posts about java

Related posts about multithreading