What should I use to get semantics equivalent to AutoResetEvent in Java? (See this question for ManualResetEvent).
A:
I believe what you're looking for is either a CyclicBarrier or a CountDownLatch.
MrWiggles
2009-07-07 13:43:48
CountDownLatch helped a bit, but it's not exactly equivalent.Come on StackOverflow - it's impossible nobody implemented this yet...
ripper234
2009-07-07 18:30:19
+3
A:
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");
}
}
}
(Apologies for not indenting the Java code by 4 spaces as suggested in this site's Formatting Reference.)
bobkart
2009-07-26 04:01:51