简体   繁体   English

替代等待并在Java中进行通知

[英]Substitute for wait and notify in java

Is there any substitute for wait/notify in java ? 在Java中是否可以替代wait / notify?

I have two threads: 我有两个线程:

thread1:
run() {
 while(true) {      
  data = getDataFromDatabase()
  changedData = performSomeChanges(data)
  commitUpdateDataToDatabase(changedDate)
  (send signal to thread2 to start and wait for signal for next repetition)
 }  
}

thread2:
run() {
 while(true) {      
  (wait for signal from thread1)
  data = getDataFromDatabase()
  changedData = performSomeChanges(data)
  commitUpdateDataToDatabase(changedDate)
  (send signal to thread1)      
 }  
}

and I want have some kind of synchranization between them. 我希望它们之间有某种同步。 Now I use wait / notify on special common Object for this purpose. 现在,我为此目的在特殊的公共对象上使用等待/通知。

Firstly, the simple way to implement your example only uses one thread: 首先,实现示例的简单方法仅使用一个线程:

run() {
    while(true) {
        // old thread 1 code      
        data = getDataFromDatabase()
        changedData = performSomeChanges(data)
        commitUpdateDataToDatabase(changedDate)
        // old thread 2 code
        data = getDataFromDatabase()
        changedData = performSomeChanges(data)
        commitUpdateDataToDatabase(changedDate)
    }  
}

There is no obvious (to me) advantage in having the execution alternate between two threads. (对我而言)在两个线程之间交替执行没有明显的优势。 And there a couple of obvious disadvantages; 还有两个明显的缺点; ie complexity, and the (smallish) performance hit of the synchronization and thread switching. 即复杂性,以及同步和线程切换的(较小)性能损失。


But assuming that you do have a legitimate reason for alternating between two threads, then there are lots of ways of doing it: 但是假设您确实有理由在两个线程之间进行交替,那么有很多方法可以做到:

  • Using wait and notify ... as you are currently doing. 正在使用wait and notify ...。 (IMO, there is no real need to find an alternative. They work just fine, if used properly! Admittedly, some Java programmers haven't mastered this ...) (IMO,没有真正的需要找到一种替代,他们工作得很好,如果使用得当!诚然,一些Java程序员还没有掌握这...)

  • Using java.util.concurrent.Semaphore and having each thread alternate between acquiring and releasing. 使用java.util.concurrent.Semaphore并使每个线程在获取和释放之间交替。

  • Using a java.util.concurrent.Lock and alternating ownership of the lock. 使用java.util.concurrent.Lock和交替使用锁的所有权。

  • Using a BlockingQueue and passing a "token" object back and forth. 使用BlockingQueue并来回传递“令牌”对象。

  • And so on 等等

There are infinite amount of way to do it. 有无数种方法可以做到。

For example you can use ReentrantLock or CountDownLatch or ArrayBlocking or ArrayBlockingQueue 例如,您可以使用ReentrantLock或CountDownLatch或ArrayBlocking或ArrayBlockingQueue

PS: What wrong with wait / notify? PS:等待/通知有什么问题? Why you want something else? 你为什么还要别的东西?

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

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