1. 程式人生 > >【06】volatile 和 synchronized 區別

【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