在java中有一个'阻止直到条件变为真'的功能吗?

时间:2011-05-14 00:43:10

标签: java multithreading block

我正在为服务器编写一个监听器线程,目前我正在使用:

while (true){
    try {
        if (condition){
            //do something
            condition=false;
        }
        sleep(1000);

    } catch (InterruptedException ex){
        Logger.getLogger(server.class.getName()).log(Level.SEVERE, null, ex);
    }
}

使用上面的代码,我遇到了运行函数吃掉所有cpu时间循环的问题。睡眠功能有效,但它似乎是一个临时修复,而不是解决方案。

是否有某些函数会阻塞,直到变量'condition'变为'true'为止? 或者是不断循环标准的等待方法,直到变量的值发生变化?

6 个答案:

答案 0 :(得分:54)

这样的轮询绝对是最不受欢迎的解决方案。

我假设您有另一个线程可以使条件成立。有几种方法可以同步线程。在您的情况下最简单的是通过对象的通知:

主线程:

synchronized(syncObject) {
    try {
        // Calling wait() will block this thread until another thread
        // calls notify() on the object.
        syncObject.wait();
    } catch (InterruptedException e) {
        // Happens if someone interrupts your thread.
    }
}

其他主题:

// Do something
// If the condition is true, do the following:
synchronized(syncObject) {
    syncObject.notify();
}

syncObject本身可以是一个简单的Object

还有许多其他的线程间通信方式,但使用哪种方式取决于你正在做什么。

答案 1 :(得分:39)

EboMike's answerToby's answer都在正确的轨道上,但它们都包含致命的缺陷。该漏洞被称为丢失通知

问题是,如果一个线程调用foo.notify(),它将不会做任何事情,除非某个其他线程已经在foo.wait()调用中休眠。对象foo不记得已通知。

除非线程在foo上同步,否则您无法调用foo.wait()foo.notify()。这是因为避免丢失通知的唯一方法是使用互斥锁保护条件。如果做得好,它看起来像这样:

消费者主题:

try {
    synchronized(foo) {
        while(! conditionIsTrue()) {
            foo.wait();
        }
        doSomethingThatRequiresConditionToBeTrue();
    }
} catch (InterruptedException e) {
    handleInterruption();
}

制作人主题:

synchronized(foo) {
    doSomethingThatMakesConditionTrue();
    foo.notify();
}

更改条件的代码和检查条件的代码全部在同一对象上同步,并且消费者线程在等待之前显式测试条件。当条件已经为真时,消费者无法错过通知并最终在wait()调用中停留。

另请注意,wait()处于循环中。这是因为,在一般情况下,当消费者重新获得foo锁定并唤醒时,某些其他线程可能会再次使该条件成为错误。即使 程序中无法实现这一点,但在某些操作系统中,即使未调用foo.wait()foo.notify()也可能返回。这被称为虚假唤醒,并且允许它发生,因为它使等待/通知更容易在某些操作系统上实现。

答案 2 :(得分:18)

与EboMike的答案类似,您可以使用类似于wait / notify / notifyAll的机制,但已准备好使用Lock

例如,

public void doSomething() throws InterruptedException {
    lock.lock();
    try {
        condition.await(); // releases lock and waits until doSomethingElse is called
    } finally {
        lock.unlock();
    }
}

public void doSomethingElse() {
    lock.lock();
    try {
        condition.signal();
    } finally {
        lock.unlock();
    }
}

你要等待另一个线程通知的某些条件(在这种情况下调用doSomethingElse),那时第一个线程将继续......

在内在同步上使用Lock有很多优点,但我只是希望有一个显式的Condition对象来表示条件(你可以拥有多个,这对于生产者这样的东西来说是个不错的选择 - 消费)。

另外,我不禁注意到你如何处理示例中的中断异常。您可能不应该像这样使用异常,而是使用Thread.currentThrad().interrupt重置中断状态标志。

这是因为如果抛出异常,中断状态标志将被重置(它说“我不再记得被打断,我不能告诉其他人,如果他们要求我就是“)和另一个过程可能依赖于这个问题。例如,其他东西已经实施了基于此的中断策略...... phew。另一个例子可能是您是中断策略,而while(true)可能已经实现为while(!Thread.currentThread().isInterrupted()(这也会使您的代码更具社交性。)

因此,总而言之,当您想要使用Condition时,使用Lock等同于使用wait / notify / notifyAll,记录是邪恶的,吞咽InterruptedException是淘气的;)

答案 3 :(得分:14)

由于没有人使用CountDownLatch发布解决方案。怎么样:

public class Lockeable {
    private final CountDownLatch countDownLatch = new CountDownLatch(1);

    public void doAfterEvent(){
        countDownLatch.await();
        doSomething();
    }

    public void reportDetonatingEvent(){
        countDownLatch.countDown();
    }
}

答案 4 :(得分:5)

您可以使用semaphore

当条件不满足时,另一个线程获取信号量 您的主题会尝试使用acquireUninterruptibly()来获取它 或tryAcquire(int permits, long timeout, TimeUnit unit)并将被阻止。

当条件满足时,信号量也被释放,你的线程将获得它。

您也可以尝试使用SynchronousQueueCountDownLatch

答案 5 :(得分:4)

无锁解决方案(?)

我有同样的问题,但我想要一个没有使用锁的解决方案。

问题:我最多只有一个线程从队列消耗。多个生产者线程不断插入队列,需要通知消费者是否在等待。该队列是无锁的,因此使用锁通知会导致生产者线程中出现不必要的阻塞。每个生产者线程需要先获取锁,然后才能通知等待的消费者。我相信我使用LockSupportAtomicReferenceFieldUpdater想出了一个无锁解决方案。如果JDK中存在无锁屏障,我无法找到它。 CyclicBarrierCoundDownLatch都在我内部使用锁定。

这是我稍微缩写的代码。需要明确的是,此代码只允许 一个 线程一次等待。可以通过使用某种类型的原子集合来存储多个所有者(ConcurrentMap可能有效)来修改它以允许多个等待者/消费者。

我使用过这段代码,似乎有效。我没有广泛测试过它。我建议您在使用前阅读LockSupport的文档。

/* I release this code into the public domain.
 * http://unlicense.org/UNLICENSE
 */

import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.concurrent.locks.LockSupport;

/**
 * A simple barrier for awaiting a signal.
 * Only one thread at a time may await the signal.
 */
public class SignalBarrier {
    /**
     * The Thread that is currently awaiting the signal.
     * !!! Don't call this directly !!!
     */
    @SuppressWarnings("unused")
    private volatile Thread _owner;

    /** Used to update the owner atomically */
    private static final AtomicReferenceFieldUpdater<SignalBarrier, Thread> ownerAccess =
        AtomicReferenceFieldUpdater.newUpdater(SignalBarrier.class, Thread.class, "_owner");

    /** Create a new SignalBarrier without an owner. */
    public SignalBarrier() {
        _owner = null;
    }

    /**
     * Signal the owner that the barrier is ready.
     * This has no effect if the SignalBarrer is unowned.
     */
    public void signal() {
        // Remove the current owner of this barrier.
        Thread t = ownerAccess.getAndSet(this, null);

        // If the owner wasn't null, unpark it.
        if (t != null) {
            LockSupport.unpark(t);
        }
    }

    /**
     * Claim the SignalBarrier and block until signaled.
     *
     * @throws IllegalStateException If the SignalBarrier already has an owner.
     * @throws InterruptedException If the thread is interrupted while waiting.
     */
    public void await() throws InterruptedException {
        // Get the thread that would like to await the signal.
        Thread t = Thread.currentThread();

        // If a thread is attempting to await, the current owner should be null.
        if (!ownerAccess.compareAndSet(this, null, t)) {
            throw new IllegalStateException("A second thread tried to acquire a signal barrier that is already owned.");
        }

        // The current thread has taken ownership of this barrier.
        // Park the current thread until the signal. Record this
        // signal barrier as the 'blocker'.
        LockSupport.park(this);
        // If a thread has called #signal() the owner should already be null.
        // However the documentation for LockSupport.unpark makes it clear that
        // threads can wake up for absolutely no reason. Do a compare and set
        // to make sure we don't wipe out a new owner, keeping in mind that only
        // thread should be awaiting at any given moment!
        ownerAccess.compareAndSet(this, t, null);

        // Check to see if we've been unparked because of a thread interrupt.
        if (t.isInterrupted())
            throw new InterruptedException();
    }

    /**
     * Claim the SignalBarrier and block until signaled or the timeout expires.
     *
     * @throws IllegalStateException If the SignalBarrier already has an owner.
     * @throws InterruptedException If the thread is interrupted while waiting.
     *
     * @param timeout The timeout duration in nanoseconds.
     * @return The timeout minus the number of nanoseconds that passed while waiting.
     */
    public long awaitNanos(long timeout) throws InterruptedException {
        if (timeout <= 0)
            return 0;
        // Get the thread that would like to await the signal.
        Thread t = Thread.currentThread();

        // If a thread is attempting to await, the current owner should be null.
        if (!ownerAccess.compareAndSet(this, null, t)) {
            throw new IllegalStateException("A second thread tried to acquire a signal barrier is already owned.");
        }

        // The current thread owns this barrier.
        // Park the current thread until the signal. Record this
        // signal barrier as the 'blocker'.
        // Time the park.
        long start = System.nanoTime();
        LockSupport.parkNanos(this, timeout);
        ownerAccess.compareAndSet(this, t, null);
        long stop = System.nanoTime();

        // Check to see if we've been unparked because of a thread interrupt.
        if (t.isInterrupted())
            throw new InterruptedException();

        // Return the number of nanoseconds left in the timeout after what we
        // just waited.
        return Math.max(timeout - stop + start, 0L);
    }
}

为了给出一个模糊的使用示例,我将采用james large的例子:

SignalBarrier barrier = new SignalBarrier();

消费者线程(单数,不是复数!):

try {
    while(!conditionIsTrue()) {
        barrier.await();
    }
    doSomethingThatRequiresConditionToBeTrue();
} catch (InterruptedException e) {
    handleInterruption();
}

生产者线程:

doSomethingThatMakesConditionTrue();
barrier.signal();