一个关于线程安全的示例

时间:2021-05-24 02:11:00   收藏:0   阅读:0
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

技术图片

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!