Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java: how can I make thread watch over another thread?

Sorry if the question is quite simple. I am a beginner.

I have to create thread that calulates something, while the first thread works the other one have to measure if the first thread calculate the function in specified time. If not, it has to throw exception. Else it returns the answer.

like image 240
Johnny Avatar asked Jan 04 '11 17:01

Johnny


3 Answers

I'd take the java.util.concurrent components - simple example

public void myMethod() {
    // select some executor strategy
    ExecutorService executor = Executors.newFixedThreadPool(1);
    Future f = executor.submit(new Runnable() {
        @Override
        public void run() {
            heresTheMethodToBeExecuted();
        }
    });
    try {
        f.get(1000, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        // do something clever
    } catch (ExecutionException e) {
        // do something clever
    } catch (TimeoutException e) {
        // do something clever
    }
}
like image 157
mtraut Avatar answered Oct 14 '22 00:10

mtraut


Have your thread notify a synchronization object when it is done and have your other thread wait x number of milliseconds for it to finish.

public class Main {

private static final Object mThreadLock = new Object();

static class DoTaskThread extends Thread {

    public void run() {

            try {
                int wait = new Random().nextInt(10000);
                System.out.println("Waiting " + wait + " ms");
                Thread.sleep(wait);
            } catch (InterruptedException ex) {
            }
            synchronized (mThreadLock) {
                mThreadLock.notifyAll();
            }

        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        synchronized (mThreadLock) {
            DoTaskThread thread = new DoTaskThread();
            thread.start();

            try {
                // Only wait 2 seconds for the thread to finish
                mThreadLock.wait(2000);
            } catch (InterruptedException ex) {
            }

            if (thread.isAlive()) {
                throw new RuntimeException("thread took too long");
            } else {
                System.out.println("Thread finished in time");
            }
        }
    }
}
like image 35
Andrew T Finnell Avatar answered Oct 13 '22 23:10

Andrew T Finnell


join is a lot simpler than using a lock.

join (millis)
Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.

Example code:

Thread calcThread = new Thread(new Runnable(){
    @Override
    public void run() {
        //some calculation            
    }
});
calcThread.start();

//wait at most 2secs for the calcThread to finish.
calcThread.join(2000);

//throw an exception if the calcThread hasn't completed.
if(calcThread.isAlive()){
    throw new SomeException("calcThread is still running!");
}
like image 24
dogbane Avatar answered Oct 13 '22 22:10

dogbane