AutoResetEvent, ManualResetEvent是C#中常用的线程同步方法,在Java中可以模拟,AutoResetEvent使用Semaphore,增加的是许可证数量,程序里只有一个许可证,那么当这个许可被使用后,就会自动锁定。相反,ManualResetEvent使用countdownlatch,增加的是“latch”,也就是障碍,或者门闩;当障碍解除时,所有程序都可以运行而不被阻塞,如果要实现同步,就必须manual reset,也就是手动加latch。
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class AutoResetEvent
{
private final Semaphore event;
private final Integer mutex;
public AutoResetEvent(boolean signalled)
{
event = new Semaphore(signalled ? 1 : 0);
mutex = new Integer(-1);
}
public void set()
{
synchronized (mutex)
{
if (event.availablePermits() == 0)
{
event.release();
}
}
}
public void reset()
{
event.drainPermits();
}
public void waitOne() throws InterruptedException
{
event.acquire();
}
public boolean waitOne(int timeout, TimeUnit unit) throws InterruptedException
{
return event.tryAcquire(timeout, unit);
}
public boolean isSignalled()
{
return event.availablePermits() > 0;
}
public boolean waitOne(int timeout) throws InterruptedException
{
return waitOne(timeout, TimeUnit.MILLISECONDS);
}
}
AutoResetEvent在MSDN中的例子程序在http://msdn.microsoft.com/en-us/library/system.threading.autoresetevent.aspx
我们可以改写一个java版本,用的是java版本的AutoResetEvent
import java.util.Date;