多线程共享变量 count++ —— 计数功能

public class Counter {
public static int count = 0;
public synchronized static void inc() {
count++;

}

 public static void main(String[] args) {
        // 同时启动1000个线程,去进行i++计算,看看实际结果
        for (int i = 0; i < 1000; i++) {
            new Thread(new Runnable() {
                public void run() {
                    Counter.inc();
                }
            }).start();
        }
        // 休眠1秒,等待前面线程累加操作完成
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("运行结果:Counter.count=" + Counter.count);
    }

 

posted @ 2017-12-25 14:58  极客船长  阅读(1334)  评论(0编辑  收藏  举报