zoukankan      html  css  js  c++  java
  • synchronized和vilatile

    第一个程序

    public class Test06 implements Runnable{
    
        public int a = 0;
        
        public static void main(String[] args) throws InterruptedException {
            Test06 r = new Test06();
            Thread[] t = new Thread[100];
            for(int i = 0;i < 100;i++)
                t[i] = new Thread(r);
            for(int j = 0;j < 100;j++)
                t[j].start();
            Thread.currentThread().sleep(2000);
            System.out.println(r.a);
    
        }
    
        @Override
        public  void run() {
            int b = a+1;
            try {
                Thread.currentThread().sleep(10);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            a = b;
        }
    
    }

    输出为?

    第二个程序

    public class Test06 implements Runnable{
    
        public int a = 0;
        
        public static void main(String[] args) throws InterruptedException {
            Test06 r = new Test06();
            Thread[] t = new Thread[100];
            for(int i = 0;i < 100;i++)
                t[i] = new Thread(r);
            for(int j = 0;j < 100;j++)
                t[j].start();
            Thread.currentThread().sleep(2000);
            System.out.println(r.a);
    
        }
    
        @Override
        public  synchronized void run() {
            int b = a+1;
            try {
                Thread.currentThread().sleep(10);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            a = b;
        }
    
    }

    输出为?

    第三个程序

    public class Test06 implements Runnable{
    
        public volatile int a = 0;
        
        public static void main(String[] args) throws InterruptedException {
            Test06 r = new Test06();
            Thread[] t = new Thread[100];
            for(int i = 0;i < 100;i++)
                t[i] = new Thread(r);
            for(int j = 0;j < 100;j++)
                t[j].start();
            Thread.currentThread().sleep(2000);
            System.out.println(r.a);
    
        }
    
        @Override
        public  void run() {
            int b = a+1;
            try {
                Thread.currentThread().sleep(10);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            a = b;
        }
    
    }

    输出为?

    三个程序中只有第二个能保证输出的为100

  • 相关阅读:
    正则表达式
    查看当前文件大小
    logging日志快速上手
    kafka消息队列的使用
    修改文件权限给指定的用户
    使用Dockerfile构建镜像
    k8s 常用命令总结
    k8s pod.yaml配置文件参数
    Linux安装依赖包
    Freeswitch配置SIP网关拨打外部
  • 原文地址:https://www.cnblogs.com/YESheng/p/3659418.html
Copyright © 2011-2022 走看看