一个关于线程安全的示例

public class ThreadDemo {
    //1.定义一个静态变量,因为静态变量是线程共享的
    public static int count = 0;

    //2.定义一个自增的方法
    public static void add() {
        try {
            Thread.sleep(1);//让程序睡眠1s才会触发cpu的时间片转换
            count++;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 1000; i++) {
            new Thread(ThreadDemo::add).start();
        }
        //等待多线程运行完
        Thread.sleep(5000);
        System.out.println("result:->" + count);
    }
}

运行结果会是:result:->小于等于1000

 

posted @ 2021-05-08 19:24  WK_BlogYard  阅读(54)  评论(0编辑  收藏  举报