簡體   English   中英

Java並發-如何正確鎖定和釋放線程

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

我想了解如何在沒有Semafor或CountdownLatch的情況下正確使用等待和通知。 讓我們舉一個簡單的例子

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方法放在同步塊中?

是的,需要將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();
}

暫無
暫無

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

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