可能存在另一个线程时的线程同步

时间:2016-09-27 07:07:30

标签: java multithreading synchronization

我有一个执行一些计算的线程,每个计算都有一个id。 每次计算都会启动一个新线程。 处理完成后,数据将写入与其id相对应的数据库中。

可能(可能会或可能不会)是另一个请求,这需要来自其他线程的计算结果。 它在数据库中查找id,如果找到它将返回结果。 如果不是,则需要检查计算是否已在进行中     如果是,请等待计算完成。完成后唤醒,从数据库中获取数据并返回。     如果没有运行计算,则开始计算并等待。完成后唤醒,从数据库中获取数据并返回。

The pseudo code is as follow:
CalculationClass
    receive a request id from a Consumer
    add id to CalculatingIds List
    when calculated
        write data to DB
        remove id from CalculatingIds List

GetDataClass
    look for the the result corresponding to id
    if found return data
    else check if the id is present in the CalculatingIds List
        if present, wait and wake up when data is available
        if not present, pass the id to the Consumer Queue. Wait and wake up when data is available

当数据尚未为GetDataClass做好准备时,我无法找到同步2个线程的方法。我正在考虑为每个计算创建一个新对象,然后使用它来同步2个线程。

synchronize(lock)
  if(noData && calculationRunning)
    lock.wait();
  else
    queue.add(id)
    CalculatingIds.add(id)

但在CalculationClass的情况下,我将如何处理此锁? 当GetDataClass线程不存在时,我将如何处理这种情况?

1 个答案:

答案 0 :(得分:2)

拥有一个跟踪当前正在处理的内容的集合。用锁保护它。正在处理特定条目的线程在对集合持有锁定时发出通知。完成后,它获取集合上的锁,删除条目,并通过调用notifyAll通知任何其他线程。如果一个线程在另一个线程中找到一个条目,同时它对该集合持有一个锁,它会在wait上循环,直到通知另一个线程完成为止。