autoresetevent java_Java's equivalent to .Net's AutoResetEvent?

问题

What should I use to get semantics equivalent to AutoResetEvent in Java?

(See this question for ManualResetEvent).

回答1:

@user249654's answer looked promising. I added some unit tests to verify it, and indeed it works as expected.

I also added an overload of waitOne that takes a timeout.

The code is here in case anyone else finds it useful:

Unit Test

import org.junit.Assert;

import org.junit.Test;

import static java.lang.System.currentTimeMillis;

/**

* @author Drew Noakes http://drewnoakes.com

*/

public class AutoResetEventTest

{

@Test

public void synchronisesProperly() throws InterruptedException

{

final AutoResetEvent event1 = new AutoResetEvent(false);

final AutoResetEvent event2 = new AutoResetEvent(false);

final int loopCount = 10;

final int sleepMillis = 50;

Thread thread1 = new Thread(new Runnable()

{

@Override

public void run()

{

try {

for (int i = 0; i < loopCount; i++)

{

long t = currentTimeMillis();

event1.waitOne();

Assert.assertTrue("Time to wait should be within 5ms of sleep time",

Math.abs(currentTimeMillis() - t - sleepMillis) < 5);

Thread.sleep(sleepMillis);

t = currentTimeMillis();

event2.set();

Assert.assertTrue("Time to set should be within 1ms", currentTimeMillis() - t <= 1);

}

} catch (InterruptedException e) {

Assert.fail();

}

}

});

Thread thread2 = new Thread(new Runnable()

{

@Override

public void run()

{

try {

for (int i = 0; i < loopCount; i++)

{

Thread.sleep(sleepMillis);

long t = currentTimeMillis();

event1.set();

Assert.assertTrue("Time to set should be within 1ms", currentTimeMillis() - t <= 1);

t = currentTimeMillis();

event2.waitOne();

Assert.assertTrue("Time to wait should be within 5ms of sleep time",

Math.abs(currentTimeMillis() - t - sleepMillis) < 5);

}

} catch (InterruptedException e) {

Assert.fail();

}

}

});

long t = currentTimeMillis();

thread1.start();

thread2.start();

int maxTimeMillis = loopCount * sleepMillis * 2 * 2;

thread1.join(maxTimeMillis);

thread2.join(maxTimeMillis);

Assert.assertTrue("Thread should not be blocked.", currentTimeMillis() - t < maxTimeMillis);

}

@Test

public void timeout() throws InterruptedException

{

AutoResetEvent event = new AutoResetEvent(false);

int timeoutMillis = 100;

long t = currentTimeMillis();

event.waitOne(timeoutMillis);

long took = currentTimeMillis() - t;

Assert.assertTrue("Timeout should have occurred, taking within 5ms of the timeout period, but took " + took,

Math.abs(took - timeoutMillis) < 5);

}

@Test

public void noBlockIfInitiallyOpen() throws InterruptedException

{

AutoResetEvent event = new AutoResetEvent(true);

long t = currentTimeMillis();

event.waitOne(200);

Assert.assertTrue("Should not have taken very long to wait when already open",

Math.abs(currentTimeMillis() - t) < 5);

}

}

AutoResetEvent with overload that accepts a timeout

public class AutoResetEvent

{

private final Object _monitor = new Object();

private volatile boolean _isOpen = false;

public AutoResetEvent(boolean open)

{

_isOpen = open;

}

public void waitOne() throws InterruptedException

{

synchronized (_monitor) {

while (!_isOpen) {

_monitor.wait();

}

_isOpen = false;

}

}

public void waitOne(long timeout) throws InterruptedException

{

synchronized (_monitor) {

long t = System.currentTimeMillis();

while (!_isOpen) {

_monitor.wait(timeout);

// Check for timeout

if (System.currentTimeMillis() - t >= timeout)

break;

}

_isOpen = false;

}

}

public void set()

{

synchronized (_monitor) {

_isOpen = true;

_monitor.notify();

}

}

public void reset()

{

_isOpen = false;

}

}

回答2:

class AutoResetEvent {

private final Object monitor = new Object();

private volatile boolean open = false;

public AutoResetEvent(boolean open) {

this.open = open;

}

public void waitOne() throws InterruptedException {

synchronized (monitor) {

while (open == false) {

monitor.wait();

}

open = false; // close for other

}

}

public void set() {

synchronized (monitor) {

open = true;

monitor.notify(); // open one

}

}

public void reset() {//close stop

open = false;

}

}

回答3:

I was able to get CyclicBarrier to work for my purposes.

Here is the C# code I was trying to reproduce in Java (it's just a demonstration program I wrote to isolate the paradigm, I now use it in C# programs I write to generate video in real time, to provide accurate control of the frame rate):

using System;

using System.Timers;

using System.Threading;

namespace TimerTest

{

class Program

{

static AutoResetEvent are = new AutoResetEvent(false);

static void Main(string[] args)

{

System.Timers.Timer t = new System.Timers.Timer(1000);

t.Elapsed += new ElapsedEventHandler(delegate { are.Set(); });

t.Enabled = true;

while (true)

{

are.WaitOne();

Console.WriteLine("main");

}

}

}

}

and here is the Java code I came up with to do the same thing (using the CyclicBarrier class as suggested in a previous answer):

import java.util.Timer;

import java.util.TimerTask;

import java.util.concurrent.CyclicBarrier;

public class TimerTest2 {

static CyclicBarrier cb;

static class MyTimerTask extends TimerTask {

private CyclicBarrier cb;

public MyTimerTask(CyclicBarrier c) { cb = c; }

public void run() {

try { cb.await(); }

catch (Exception e) { }

}

}

public static void main(String[] args) {

cb = new CyclicBarrier(2);

Timer t = new Timer();

t.schedule(new MyTimerTask(cb), 1000, 1000);

while (true) {

try { cb.await(); }

catch (Exception e) { }

System.out.println("main");

}

}

}

回答4:

One more extension to the solution from the accepted answer in case you would like to know whether your wait finished with timeout or with event set (which is exactly what .NET AutoResetEvent does).

public boolean waitOne(long timeout) throws InterruptedException {

synchronized (monitor) {

try {

long t = System.currentTimeMillis();

while (!isOpen) {

monitor.wait(timeout);

// Check for timeout

if (System.currentTimeMillis() - t >= timeout)

break;

}

return isOpen;

}

finally {

isOpen = false;

}

}

}

回答5:

import java.util.concurrent.TimeUnit;

import java.util.concurrent.locks.Condition;

import java.util.concurrent.locks.ReentrantLock;

public class AutoResetEvent {

private volatile boolean _signaled;

private ReentrantLock _lock;

private Condition _condition;

public AutoResetEvent(boolean initialState) {

_signaled = initialState;

_lock = new ReentrantLock();

_condition = _lock.newCondition();

}

public void waitOne(long miliSecond) throws InterruptedException {

_lock.lock();

try {

while (!_signaled)

_condition.await(miliSecond, TimeUnit.MILLISECONDS);

_signaled = false;

} finally {

_lock.unlock();

}

}

public void waitOne() throws InterruptedException {

_lock.lock();

try {

while (!_signaled)

_condition.await();

_signaled = false;

} finally {

_lock.unlock();

}

}

public void set() {

_lock.lock();

try {

_condition.signal();

_signaled = true;

} finally {

_lock.unlock();

}

}

public void reset() {

_lock.lock();

try {

_signaled = false;

} finally {

_lock.unlock();

}

}

}

回答6:

I believe what you're looking for is either a CyclicBarrier or a CountDownLatch.

来源:https://stackoverflow.com/questions/1091973/javas-equivalent-to-nets-autoresetevent

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
城市应急指挥系统是智慧城市建设的重要组成部分,旨在提高城市对突发事件的预防和处置能力。系统背景源于自然灾害和事故灾难频发,如汶川地震和日本大地震等,这些事件造成了巨大的人员伤亡和财产损失。随着城市化进程的加快,应急信息化建设面临信息资源分散、管理标准不统一等问题,需要通过统筹管理和技术创新来解决。 系统的设计思路是通过先进的技术手段,如物联网、射频识别、卫星定位等,构建一个具有强大信息感知和通信能力的网络和平台。这将促进不同部门和层次之间的信息共享、交流和整合,提高城市资源的利用效率,满足城市对各种信息的获取和使用需求。在“十二五”期间,应急信息化工作将依托这些技术,实现动态监控、风险管理、预警以及统一指挥调度。 应急指挥系统的建设目标是实现快速有效的应对各种突发事件,保障人民生命财产安全,减少社会危害和经济损失。系统将包括预测预警、模拟演练、辅助决策、态势分析等功能,以及应急值守、预案管理、GIS应用等基本应用。此外,还包括支撑平台的建设,如接警中心、视频会议、统一通信等基础设施。 系统的实施将涉及到应急网络建设、应急指挥、视频监控、卫星通信等多个方面。通过高度集成的系统,建立统一的信息接收和处理平台,实现多渠道接入和融合指挥调度。此外,还包括应急指挥中心基础平台建设、固定和移动应急指挥通信系统建设,以及应急队伍建设,确保能够迅速响应并有效处置各类突发事件。 项目的意义在于,它不仅是提升灾害监测预报水平和预警能力的重要科技支撑,也是实现预防和减轻重大灾害和事故损失的关键。通过实施城市应急指挥系统,可以加强社会管理和公共服务,构建和谐社会,为打造平安城市提供坚实的基础。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值