读书人

用JAVA写一个多线程程序,该如何处理

发布时间: 2012-04-26 14:01:31 作者: rapoo

用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--;    }} 

读书人网 >Java相关

热点推荐