2016-04-22 122 views
-1

我想了解如何正确使用等待并通知没有Semafor或CountdownLatch。让我们举一个简单的例子Java并发 - 如何正确锁定并释放线程

Response call(long[] l) 
{ 
    final Response r = new Response(); 
    Thread t = Thread.currentThread(); //get current thread 
    thread2(l,s -> { 
     response.setObject(s); 
     t.notify(); //wake up first thread 
    }); 
    Thread.currentThread().wait(); //wait until method thread2 finishes 
    return response; 
} 
void thread2(long[] l, Consumer c) 
{ 
    //start new thread and call 
    c.accept(resultobject); 
} 

我的行为是否可以接受?是否需要将.notify方法放入同步块中?

+0

没有。永远不要使用通知并等待线程对象。 – Savior

+1

另外,'wait'和'notify'都要求调用线程拥有该目标对象上的监视器。 – Savior

+0

请参阅Java教程:https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html wait()/ notify()机制是一种原始设施,应该用于非常具体方式来实现更高级别的同步对象。 –

回答

2

是的,需要将notify放入synchronized block。主逻辑如下:

等待对象的给定状态的线程的伪代码:

synchronized(mutex) { 
    while (object state is not the expected one) { 
     mutex.wait(); 
    } 
    // Code here that manipulates the Object that now has the expected state 
} 

用于修改对象的状态和想要将线程伪代码通知其他线程:

synchronized(mutex) { 
    // Code here that modifies the state of the object which could release 
    // the threads waiting for a given state 
    mutex.notifyAll(); 
}