复制代码

【06】volatile 和 synchronized 区别

synchronized 同步,解决多线程 访问临界区的问题,作用于实例 ,但是 修饰 static 方法 是 作用.class 锁

volatile 变量的线程可见,换句不太恰当的话,就是扔在了线程栈外(共享区域)

 

volatile 实例1,这里有个坑 while(flag)  会被jvm 优化 成 if(flag){ while(true){} }  (坑) 

package Concurrency;

public class volatile1 extends Thread {
    private volatile boolean flag = true;
    public void run(){
        while(this.flag == true){
        }
        System.out.println("出来了");
    }
    public void setFlag(boolean flag){
        this.flag = flag;
    }
    public static   void main(String []arg)throws InterruptedException
    {
        volatile1 v = new volatile1();
        v.start();;
        Thread.sleep(1000);
        v.setFlag(false);
        Thread.sleep(2000);
        System.out.println("Main 走了");
    }
}
View Code

重入问题 ,那个准则,不要进行 申请内存,静态地址,非重入函数,(剩下的重入锁 学到再说)

多线程重入

package Concurrency;

public class syncDubbo1 {
    public synchronized  void func1(){
        System.out.println("Func1");
        func2();
    }
    public synchronized  void func2(){
        System.out.println("func2");
        func3();
    }
    public synchronized  void func3(){
        System.out.println("func3");
    }


    public static void main(String []arg){
        syncDubbo1 s = new syncDubbo1();
        Thread t1 =new Thread(new Runnable() {
            @Override
            public void run() {
                s.func1();
            }
        });
        t1.start();

        s.func2();

    }
}
View Code

父子类的重入

package Concurrency;

import java.util.concurrent.SubmissionPublisher;

public class syncDubbo2 {
    static class Father{
        static int i =10;
        public synchronized void operator(){
            i--;
            try {
                System.out.println("Father sub Num "+i);
                Thread.sleep(100);
            }catch (InterruptedException e){
                e.printStackTrace();;
            }
        }
    }
    static class Sub extends Father{
        @Override
        public synchronized void operator(){
            while(i>0)
            {
                i--;
                try {
                    System.out.println("Son  sub Num "+i);
                    Thread.sleep(100);
                    super.operator();
                }catch (InterruptedException e){
                    e.printStackTrace();;
                }
            }
        }
    }
    public static void  main(String []arg){
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                Sub s =  new Sub();
                s.operator();
            }
        });
        t1.start();
    }
}
View Code

 

posted @ 2018-11-29 17:44  pg633  阅读(146)  评论(0编辑  收藏  举报