Python "Event" equivalent in Java?

What is the closest thing in Java (maybe an idiom) to threading.Event in Python?

+5
source share
2 answers

Object.wait() Object.notify()/ Object.notifyAll().

Or Condition.await()and Condition.signal()/ Condition.signalAll()for Java 5+.

Edit: Since the python specification is similar to how we normally expect the Java implementation to look like this:

class Event {
    Lock lock = new ReentrantLock();
    Condition cond = lock.newCondition();
    boolean flag;
    public void doWait() throws InterruptedException {
        lock.lock();
        try {
            while (!flag) {
                cond.await();
            }
        } finally {
            lock.unlock();
        }
    }
    public void doWait(float seconds) throws InterruptedException {
        lock.lock();
        try {
            while (!flag) {
                cond.await((int)(seconds * 1000), TimeUnit.MILLISECONDS);
            }
        } finally {
            lock.unlock();
        }
    }
    public boolean isSet() {
        lock.lock();
        try {
            return flag;
        } finally {
            lock.unlock();
        }
    }
    public void set() {
        lock.lock();
        try {
            flag = true;
            cond.signalAll();
        } finally {
            lock.unlock();
        }
    }
    public void clear() {
        lock.lock();
        try {
            flag = false;
            cond.signalAll();
        } finally {
            lock.unlock();
        }
    }
}
+7
source

A connected thread . There is a comment on the accepted answer, which suggests Semaphore or Latch . Not the same semantics as above, but convenient.

0

All Articles