Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java并发-如何正确锁定和实现线程_Java_Multithreading - Fatal编程技术网

Java并发-如何正确锁定和实现线程

Java并发-如何正确锁定和实现线程,java,multithreading,Java,Multithreading,我想了解如何在没有Semafor或CountdownLatch的情况下正确使用wait和notify。让我们举一个简单的例子 Response call(long[] l) { final Response r = new Response(); Thread t = Thread.currentThread(); //get current thread thread2(l,s -> { response.setObject(s); t.no

我想了解如何在没有Semafor或CountdownLatch的情况下正确使用wait和notify。让我们举一个简单的例子

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(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();
}
修改对象状态并希望通知其他线程的线程的伪代码:

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

不。永远不要对线程对象使用notify和wait。另外,
wait
notify
都要求调用线程拥有该目标对象上的监视器。请参阅Java教程:wait()/notify()机制是一种基本工具,应该以非常特定的方式使用它来实现更高级别的同步对象。