1. 程式人生 > >synchronized 線程同步

synchronized 線程同步

sys syn nbsp clas his this ron override println

synchronized 通常用來形容一次方法的調用,調用一旦開始,調用者必須等到方法調用返回後,才能繼續執行後續的操作。

1.demo

package demo1;
public class MyThread extends Thread {
    private  int count = 5;
    @Override
    public  void run() {
        count--;
        System.err.println("∽"+currentThread().getName()+"count:"+this.count);
    }
public static void main(String[] args){ MyThread myThread = new MyThread(); Thread t1 = new Thread(myThread,"myThread-1"); Thread t2 = new Thread(myThread,"myThread-2"); Thread t3 = new Thread(myThread,"myThread-3"); Thread t4 = new Thread(myThread,"myThread-4"); Thread t5
= new Thread(myThread,"myThread-5"); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); } }
結果輸出:

        ∽myThread-1count:2
        ∽myThread-4count:1
        ∽myThread-2count:2
        ∽myThread-3count:2
        ∽myThread-5count:0

 

描述:5個線程都會去對這個 count 變量進行操作,但是出現了重復的數據,說明沒有進行同步、共享。

2.demo:使用 synchronized 關鍵字

package demo1;

public class MyThread extends Thread {


    private  int count = 5;
    @Override
    public synchronized void run() {
        count--;
        System.err.println("∽"+currentThread().getName()+"count:"+this.count);
    }
    public  static void main(String[] args){
        MyThread  myThread = new MyThread();
        Thread t1 = new Thread(myThread,"myThread-1");
        Thread t2 = new Thread(myThread,"myThread-2");
        Thread t3 = new Thread(myThread,"myThread-3");
        Thread t4 = new Thread(myThread,"myThread-4");
        Thread t5 = new Thread(myThread,"myThread-5");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();

    }
}

結果輸出:

      ∽myThread-1count:4
      ∽myThread-3count:3
      ∽myThread-2count:2
      ∽myThread-4count:1
      ∽myThread-5count:0

 

描述:輸出的結果沒有重復的,說明同步生效了。

  1.當多個線程都去訪問 MyThread 的run 方法的時候,都會以隊列的的方式去進行訪問處理(CPU的分配)。

  2.一個線程要執行 synchronized 方法修飾的代碼塊:都會去嘗試去獲取鎖(object的鎖),如果拿到鎖,則執行 synchronized 代碼的內容;

   如果拿不到,則會不斷的去嘗試獲取這把鎖,一直到拿到為止 (多個線程去嘗試獲取這把鎖,就行形成競爭、排隊的問題)。

synchronized 線程同步