synchronized,了解一下


public class Test1 {


        /*
         * java堆内存,存放程序中所有的类实例、静态数据等变量,是多个线程共享的,
         * 工作内存放的是该线程从堆内存中拷贝过来的变量以及访问方法所取得的局部变量,是每个线程私有的
         * 
         * 多线程之间是不能相互传递数据通信的,只能通过共享变量
         * 执行顺序
         * 1、从堆内存复制变量到工作内存 read and load
         * 2、执行代码,处理变量 use and assign
         * 3、刷新堆内存相关内容 store and write
         * 
         * 
         * 线程在引用变量时不能直接从堆内存中引用,这就出现了时序问题
         * 
         * 多个线程同时操作一个数据机构的时候产生了相互修改和串行的情况,
         * 没有保证数据的一致性,通常称这种设计的代码为 线程不安全
         * 
         */

    static class Count {
        public int  num = 0 ; 
//      synchronized  同步锁机制 同一时刻最多只有一个线程执行该代码,其他线程访问时将阻塞
//      一种是加在方法上面, 一种是synchronized(this) 锁对象

        public synchronized void add() { //线程安全
//      public void add() {  线程不安全
            try {
                Thread.sleep(11);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            num +=1 ; 
            System.err.println(Thread.currentThread().getName()
                    + " = " 
                    +num);

        }
    }
    static class MyThread extends Thread{
        private Count count ;
        public MyThread( Count count) {
            this.count = count;
        }
        @Override
        public void run() {

            count.add();
        }
    }

    public static void main(String[] args) {

        Count count = new Count();
        for (int i = 0; i < 5; i++) {
            MyThread myThread = new MyThread(count);
            myThread.start();

            try {

                Thread.sleep(11);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.err.println(count.num);

        }
    }
}

猜你喜欢

转载自blog.csdn.net/java_sparrow/article/details/81221837