简体   繁体   English

Java并发-如何正确锁定和释放线程

[英]Java concurrency - how to properly lock and realease thread

I would like to understand how do i properly use wait and notify without Semafor or CountdownLatch. 我想了解如何在没有Semafor或CountdownLatch的情况下正确使用等待和通知。 lets have a simple example 让我们举一个简单的例子

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

Is my behavior acceptable? 我的行为可以接受吗? is it required to put .notify method in a synchronized block? 是否需要将.notify方法放在同步块中?

Yes it is required to put notify into a synchronized block . 是的,需要将notify放入synchronized block The main logic is the following: 主要逻辑如下:

Pseudo code of the threads waiting for a given state of an Object: 等待对象给定状态的线程的伪代码:

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

Pseudo code of the threads that modify the state of the Object and want to notify other threads: 修改对象状态并要通知其他线程的线程的伪代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM