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

原文地址:https://www.cnblogs.com/YESheng/p/3659418.html