/**
 * Thread synchronization
 *
 * Sample of basic thread synchronization facilities.
 */

class Counter
{
    /**
     * Increment
     *
     * params:  
     * return:  
     */
    public synchronized method increment ()
    {
        System.sleep(System.random(0,4) * 10)

        @count.increment()
    }

    
    /**
     * Decrement
     *
     * params:  
     * return:  
     */
    public synchronized method decrement ()
    {
        System.sleep(System.random(0,4) * 10)

        @count.decrement()
    }

    
    /**
     * Get count
     *
     * params:  
     * return:  count (Number)
     */
    public method get_count ()
    {
        // synchronized block
        synchronized (self) {
            @count
        }
    }

    
    /**
     * Initialize
     *
     * params:  
     * return:  
     */
    method initialize ()
    {
        field @count(0)

        System.random_seed(System.time())
    }
}


/**
 * Thread start point
 *
 * params:  counter
 * return:  
 */
method run (counter)
{
    counter.increment()
    counter.decrement()
    counter.increment()
}


/**
 * Main
 *
 * params:  
 * return:  
 */
method main ()
{
    counter = Counter.new()
    run = get_method("run")
    threads = Array.new()

    // create threads
    for (i; 0..4) {
        threads.add(System.Concurrent.Thread.new(run))
    }

    // start threads
    for (i; 0..4) {
        threads[i].start(self, counter)
    }

    // join threads
    for (i; 0..4) {
        threads[i].join()
    }

    print("count: " + counter.get_count())
}

main()