簡體   English   中英

在Java中:如何讓線程監視另一個線程?

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

對不起,如果問題很簡單。 我是初學者。

我必須創建調用某些東西的線程,而第一個線程工作,另一個必須測量第一個線程是否在指定時間內計算函數。 如果沒有,它必須拋出異常。 否則它會返回答案。

我將采用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
    }
}

讓你的線程在完成后通知同步對象,並讓你的另一個線程等待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比使用鎖更簡單。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM