在Java中:如何让线程监视另一个线程?

时间:2011-01-04 17:21:28

标签: java multithreading

很抱歉,问题很简单。我是初学者。

我必须创建用于计算某些东西的线程,而第一个线程工作,另一个必须测量第一个线程是否在指定时间内计算函数。如果没有,它必须抛出异常。否则它会返回答案。

4 个答案:

答案 0 :(得分:5)

我将使用java.util.concurrent组件 - 简单示例

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

答案 1 :(得分:3)

让你的线程在完成时通知同步对象,让你的另一个线程等待x毫秒才能完成。

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

答案 2 :(得分:2)

join比使用锁更简单。

  

<强> join (millis)   
最多等待millis毫秒   让这个线程死掉。超时为0   意味着永远等待。

示例代码:

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!");
}

答案 3 :(得分:1)

相关问题