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

  • 相关阅读:
    Wayland中的跨进程过程调用浅析
    设计模式总结
    C语言---整型字符串转换
    抽象工厂模式
    SVNclient安装与使用
    [置顶] MyEclipse下安装插件方法(properties文件编辑器Propedit为例)
    脑筋急转弯的歧义性
    脑筋急转弯的歧义性
    从和式积分到定积分
    从和式积分到定积分
  • 原文地址:https://www.cnblogs.com/YESheng/p/3659418.html
Copyright © 2011-2022 走看看