2017-02-14 33 views
-5

我需要阻止当前线程,直到我调用以下两种方法之一(我创建的)。如何在用户调用特定方法之前阻止当前线程?

  • onJobComplete()
  • onJobError(Throwable t)

这些方法从不同的线程调用。

这可能与一个CountDownLatch(1)? (当这两种方法中的任何一种被调用时,我会递减)。似乎我只能使用CountDownLatch新的线程。

如果不是,我该如何做到这一点?

背景:https://github.com/ReactiveX/RxJava/issues/5094(我需要从第三方库异步使下面的同步onRun()法)

/** 
    * The actual method that should to the work. 
    * It should finish w/o any exception. If it throws any exception, 
    * {@link #shouldReRunOnThrowable(Throwable, int, int)} will be 
    * automatically called by this library, either to dismiss the job or re-run it. 
    * 
    * @throws Throwable Can throw and exception which will mark job run as failed 
    */ 
    abstract public void onRun() throws Throwable; 

更多信息:由于库的限制,我无法控制时onRun()开始。该库需要这种方法是同步的,因为它的完成会自动向库发信号通知“作业”已成功完成。我想“暂停”onRun()并阻止它返回,启动我自己的异步线程,并且“恢复”onRun()(允许onRun()返回),一旦我的异步线程完成。

+0

我会,如果你使用的是Java的旧版本或)更喜欢使用对象的wait(和通知

class YourJob { boolean markFinished = false; // is the job explicitly marked as finished final Lock lock = new ReentrantLock(); final Condition finished = lock.newCondition(); public void onRun() { // your main logic lock.lock(); try { while(!markFinished) { finished.await(); } } finally { lock.unlock(); } } public void complete() { // the name onComplete is misleading, as onXxx is usually // used as method to be implemented in template method lock.lock(); try { complete = true; finished.signalAll(); } finally { lock.unlock(); } } } 

类似这两个方法设置一个布尔值并且运行休眠直到变量发生变化,或者'wait/notify'怎么样? –

+1

那么,你的“当前线程”在做什么?问题可以更具体吗? 'wait' /'notify'(或'await' /'signal')似乎是你可能会看到的东西。但也有其他更好的并发构造,比如'Future'。你的问题太模糊,人们建议 –

+0

当然,使用'未来'。 – dimo414

回答

0

使用锁定和条件的示例。

class YourJob { 
    boolean markFinished = false; // is the job explicitly marked as finished 

    public void onRun() { 
     // your main logic 

     synchronized (this) { 
      while(!markFinished) { 
       wait(); 
      } 
     } 
    } 

    public synchronized void complete() { 
     complete = true; 
     notifyAll(); 
    } 
} 

所以使用它:

YourJob job = new YourJob(); 
tellYourLibCallJobOnRun(job); // job.onRun() invoked asynchronously 

//..... doing something else 
// if job.onRun() is invoked in background, it will be blocked waiting 
// at the end 

job.complete(); // job.onRun() will continue after this 
相关问题