2つのスレッドがjに対して1ずつ増加する4つのスレッドを設計し、他の2つのスレッドがjに対して1ずつ減少する.プログラムを書き出します.


/**
 * @author WenQiang Wu
 * @version Dec 28, 2009
 */
public class ThreadTest {

    private int j;

    /**
     * add method
     */
    private synchronized void add() {
        j++;
        System.out.println(Thread.currentThread().getName() + "->add : " + j);
    }

    /**
     * inc method
     */
    private synchronized void inc() {
        j--;
        System.out.println(Thread.currentThread().getName() + "->inc : " + j);
    }

    /**
     * 
     * @param args
     */
    public static void main(String[] args) {
        ThreadTest tt = new ThreadTest();

        //inner class instance
        Inc inc = tt.new Inc();
        Add add = tt.new Add();

        //start thread
        for (int i = 0; i < 2; i++) {
            //start inc thread
            Thread thread = new Thread(inc);
            thread.start();

            //start add thread
            thread = new Thread(add);
            thread.start();
        }
    }

    /**
     * 
     * @author WenQiang Wu
     * @version Dec 28, 2009
     */
    class Inc implements Runnable {
        /*
         * (non-Javadoc)
         * 
         * @see java.lang.Runnable#run()
         */
        public void run() {
            for (int i = 0; i < 100; i++) {
                inc();
            }
        }
    }

    /**
     * 
     * @author WenQiang Wu
     * @version Dec 28, 2009
     */
    class Add implements Runnable {

        /* (non-Javadoc)
         * @see java.lang.Runnable#run()
         */
        public void run() {
            for (int i = 0; i < 100; i++) {
                add();
            }
        }
    }
}