简体   繁体   English

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

[英]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. 否则它会返回答案。

I'd take the java.util.concurrent components - simple example 我将采用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
    }
}

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. 让你的线程在完成后通知同步对象,并让你的另一个线程等待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");
            }
        }
    }
}

join is a lot simpler than using a lock. join比使用锁更简单。

join (millis)
Waits at most millis milliseconds for this thread to die. 最多等待millis毫秒该线程终止。 A timeout of 0 means to wait forever. 超时为0意味着永远等待。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM