Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is java's equivalent of ManualResetEvent? [duplicate]

What is java's equivalent of ManualResetEvent?

like image 482
ripper234 Avatar asked Jun 30 '09 16:06

ripper234


4 Answers

class ManualResetEvent {    private final Object monitor = new Object();   private volatile boolean open = false;    public ManualResetEvent(boolean open) {     this.open = open;   }    public void waitOne() throws InterruptedException {     synchronized (monitor) {       while (open==false) {           monitor.wait();       }     }   }    public boolean waitOne(long milliseconds) throws InterruptedException {     synchronized (monitor) {       if (open)          return true;       monitor.wait(milliseconds);         return open;     }   }    public void set() {//open start     synchronized (monitor) {       open = true;       monitor.notifyAll();     }   }    public void reset() {//close stop     open = false;   } } 
like image 200
terentev Avatar answered Sep 19 '22 13:09

terentev


The closest I know of is the Semaphore. Just use it with a "permit" count of 1, and aquire/release will be pretty much the same as what you know from the ManualResetEvent.

A semaphore initialized to one, and which is used such that it only has at most one permit available, can serve as a mutual exclusion lock. This is more commonly known as a binary semaphore, because it only has two states: one permit available, or zero permits available. When used in this way, the binary semaphore has the property (unlike many Lock implementations), that the "lock" can be released by a thread other than the owner (as semaphores have no notion of ownership). This can be useful in some specialized contexts, such as deadlock recovery.

like image 42
Lucero Avatar answered Sep 21 '22 13:09

Lucero


Try CountDownLatch with count of one.

CountDownLatch startSignal = new CountDownLatch(1);
like image 36
crafty Avatar answered Sep 22 '22 13:09

crafty


Based on:

ManualResetEvent allows threads to communicate with each other by signaling. Typically, this communication concerns a task which one thread must complete before other threads can proceed.

from here:

http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent.aspx

you possibly want to look at the Barriers in the Java concurrency package - specifically CyclicBarrier I believe:

http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/CyclicBarrier.html

It blocks a fixed number of threads until a particular event has occured. All the threads must come together at a barrier point.

like image 28
Jon Avatar answered Sep 18 '22 13:09

Jon