簡體   English   中英

鎖定或同步

[英]Lock or synchronized

我有主線程調用另一個線程。 第二個超時時間為15秒。 當前的實現是每2秒檢查一次主線程。 我需要做的是僅等待第二個線程完成,最長不超過15秒。 我想到嘗試等待和通知,但需要同步。 我正在考慮使用Lock。 我以前沒有嘗試過。 請幫幫我。

謝謝

這個想法可以實現嗎? 通過在第一個線程中的鎖定對象上使用timedwait。 一旦完成第二個線程應在鎖定對象上進行通知。 這將喚醒第一個線程。 此外,timedwait將強制最長等待15秒。

我嘗試了更新解決方案。

public class MyThread {

Object obj = new Object();
boolean isDone = false;
int timeOut = 0;
int runTime = 0;    
int id = 0;

public static void main(String[] args) throws Exception {       
    MyThread mainThread = new MyThread();

    mainThread.timeOut = Integer.valueOf(args[0]);
    mainThread.runTime = Integer.valueOf(args[1]);
    System.out.println("<---- mainThread.timeOut ---------->" + mainThread.timeOut);
    System.out.println("<---- mainThread.runTime ---------->" + mainThread.runTime);
    ChildThread childThread = new ChildThread(mainThread);
    childThread.start();        
    try {
        synchronized (mainThread.obj) {
            //Wait the current Thread for 15 seconds
            mainThread.obj.wait(mainThread.timeOut * 1000);
        }       
        System.out.println("<---- runTime Over ---------->");
        if (mainThread.isDone)
            System.out.println("<---- done ---------->");
        else
            System.out.println("<----  not done ---------->");
    } catch (InterruptedException e) {          
        e.printStackTrace();
    }
}

public void test() {        
    System.out.println("<--- In business Test method --->");    
    try {
        //Call the bussiness method which may take more time
        Thread.sleep(runTime * 1000);
        if (runTime <= timeOut)
            isDone = true;
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("<---- completes business test method -->");
}
}

class ChildThread extends Thread {          
    MyThread mainThread;
    ChildThread(MyThread mainThread) {
        this.mainThread = mainThread;
    }

    public void run() { 
        System.out.println("ChildThread: the run method");
        mainThread.test();
        //Finished the work,notify the waiting thread.
        synchronized(mainThread.obj) {
            mainThread.obj.notify();
        }
    }   
}

使用acquire()獲取等待線程以阻塞信號量 ,並讓信號線程通過release()增加它。

詳細說明

信號量是一個保持計數的同步原語。 此計數沒有內在含義,但是通常指示某種“資源”中有多少是“可用的”。 信號量具有兩個基本操作:遞增和遞減。 增量永遠不會阻塞。 如果信號量的計數為零,則減量會阻塞,而當另一個線程增加信號量時,減量會取消阻塞。 如果遞減阻止了多個線程,則每個增量僅釋放一個線程。

在當前情況下,您將創建一個初始計數(“ permits ”)為零的信號量,兩個線程可以訪問該信號量。 第一個線程通過減少信號量來等待,該信號量將阻塞線程,直到第二個線程增加信號量為止。

聽起來,FutureTask適合您的目的。 參見http://download.oracle.com/javase/6/docs/api/java/util/concurrent/FutureTask.html

基本思想是可以將第二個線程轉換為Callable,然后將其包裝在FutureTask中。 然后,您可以在FutureTask上調用帶有超時的get。

我已經用答案更新了問題。

使用WaitForSingleObject()函數,當指定的對象處於信號狀態或經過超時間隔時,該函數將返回。

WaitForSingleObject(hThread, 15000);

其中hThread是第二個線程的句柄。

暫無
暫無

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

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