日期:2014-05-20  浏览次数:20641 次

用JAVA写一个多线程程序
用JAVA写一个多线程程序,写四个线程,二个线程对这个变量++,另外两个对这个变量变量--,输出。 
大家活跃起来吧

------解决方案--------------------
Java code

public class MultiIncDec {

    private static int counter = 0;

    public static void main(String[] args) {
        // 负责增加的
        Runnable adder = new Runnable() {
            public void run() {
                for (int i = 0; i < 1e6; i++)
                    inc();
            }
        };
        // 负责减少的
        Runnable decer = new Runnable() {
            public void run() {
                for (int i = 0; i < 1e6; i++)
                    dec();
            }
        };

        // 定义线程
        Thread[] ts = new Thread[4];
        ts[0] = new Thread(adder);
        ts[1] = new Thread(adder);
        ts[2] = new Thread(decer);
        ts[3] = new Thread(decer);
        
        // 启动
        for (Thread t:ts) {
            t.start();
        }
        
        // 等待结束
        for (Thread t:ts) {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        
        // 输出结果
        System.out.println("Result: " + counter);
    }

    public static synchronized void inc() {
        counter++;
    }

    public static synchronized void dec() {
        counter--;
    }

}