zoukankan      html  css  js  c++  java
  • 线程安全问题

    线程的安全问题,单线程时,数据一般是处于安全的状态;但当多线程时,数据就容易产生安全问题。

    public class Count {
        private int num;
        public void add(){
            for(int i = 0; i< 10;i++){
                num+=i;
            }
            System.out.println(Thread.currentThread().getName()+"--"+num);
        }
    }
    public class ThreadTest {
        public static void main(String[] args) {
    
            Runnable runnable = new Runnable() {
                Count count = new Count();  //线程中定义一个对象,count
                @Override
                public void run() {
                    count.add();
                }
            };
    
            for(int i =0;i< 10;i++){
                Thread thread = new Thread(runnable);  //启动多个线程,线程中包装的是runnable这个对象
                thread.start();
    } } }

    最后的输出结果是(每次输出的结果不同,很显然,最后的结果不是正确的):

    Thread-2--91
    Thread-0--91
    Thread-1--91
    Thread-3--136
    Thread-4--181
    Thread-9--226
    Thread-5--271
    Thread-7--316
    Thread-8--406
    Thread-6--406

    原因:线程之间不能共享数据,只能从主内存中读出数据,放到自己的线程内存中,当数据修改后,再将数据刷新到主内存中,这就容易产生多线程安全问题。

  • 相关阅读:
    牛客练习赛24 E:青蛙(最短路)
    菜根谭#10
    菜根谭#9
    菜根谭#8
    菜根谭#7
    菜根谭#6
    菜根谭#5
    菜根谭#4
    菜根谭#3
    菜根谭#2
  • 原文地址:https://www.cnblogs.com/lfdingye/p/7442938.html
Copyright © 2011-2022 走看看