class Counter
{
public synchronized method increment ()
{
System.sleep(System.random(0,4) * 10)
@count.increment()
}
public synchronized method decrement ()
{
System.sleep(System.random(0,4) * 10)
@count.decrement()
}
public method get_count ()
{
synchronized (self) {
@count
}
}
method initialize ()
{
field @count(0)
System.random_seed(System.time())
}
}
method run (counter)
{
counter.increment()
counter.decrement()
counter.increment()
}
method main ()
{
counter = Counter.new()
run = get_method("run")
threads = Array.new()
for (i; 0..4) {
threads.add(System.Concurrent.Thread.new(run))
}
for (i; 0..4) {
threads[i].start(self, counter)
}
for (i; 0..4) {
threads[i].join()
}
print("count: " + counter.get_count())
}
main()