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

  • 相关阅读:
    【模板】辗转相除法
    【模板】冰茶姬(大概是全的?)
    【模板】快速幂
    【模板】线段树-区间修改
    【模板】线段树-单点修改,区间查询
    【模板】dijkstra与floyd
    【模板】SPFA(不完全详解)
    【济南集训】随机分数
    P3205 [HNOI2010]合唱队
    最大子列2
  • 原文地址:https://www.cnblogs.com/YESheng/p/3659418.html
Copyright © 2011-2022 走看看