锁定或同步

时间:2010-08-13 09:11:42

标签: java concurrency locking

我有一个调用另一个线程的主线程。第二个的超时时间是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();
        }
    }   
}

4 个答案:

答案 0 :(得分:4)

使用acquire()使Semaphore上的等待线程被阻止,并让信令线程以release()递增它。

详细说明

信号量是一个维持计数的同步原语。这个计数没有内在意义,但通常表示某种“资源”中有多少是“可用的”。信号量有两个基本操作:递增和递减。增量从不阻止。如果信号量的计数为零,则减少阻塞;当另一个线程增加信号量时,减少阻塞。如果多个线程在递减时被阻塞,则每个增量只有一个被解除阻塞。

在本例中,您创建一个信号量,其初始计数(“permits”)为零,两个线程可以访问。第一个线程通过递减信号量来等待,信号量阻塞线程,直到第二个线程递增信号量。

答案 1 :(得分:2)

听起来像FutureTask符合您的目的。见http://download.oracle.com/javase/6/docs/api/java/util/concurrent/FutureTask.html

基本思想是你可以将第二个线程转换为Callable,然后将其包装在FutureTask中。然后,您可以在FutureTask上使用超时调用get。

答案 2 :(得分:1)

我已经用答案更新了问题。

答案 3 :(得分:0)

使用WaitForSingleObject()函数,该函数在指定对象处于信号状态或超时间隔过去时返回。

WaitForSingleObject(hThread, 15000);

其中hThread是第二个线程的句柄。

相关问题