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

  • 相关阅读:
    【日语】标日初级上册单词(5-8)1
    【日语】标日初级上册单词(1-4)1
    【日语】计算机日语
    百家姓日语
    【日语】动物名称日语单词集合
    【日语】日语常用会话1000句
    【日语】编程相关日语词汇
    【日语】日语N5学习
    【日语】日语新闻核心词汇
    使用uni-app开发微信小程序之登录模块
  • 原文地址:https://www.cnblogs.com/YESheng/p/3659418.html
Copyright © 2011-2022 走看看