在Java中:我该如何使一个线程监视另一个线程?

5

如果问题很简单,我很抱歉。我是一个初学者。

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


我会重新表达你的问题。如何在Java中执行条件同步?Andrew在下面给出了很好的例子。 - overexchange
4个回答

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

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

这就是条件同步(Ordering)的体现。很好的例子。你的代码内部使用了一个锁和一个与mThreadLock对象关联的等待/进入队列。最好的条件同步示例是在此处给出的多个生产者/消费者算法,它需要一个锁和两个条件变量。 - overexchange

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

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接