2.多線程(同步類級別鎖)

多個線程多個鎖

    1.多個線程,每一個線程均可以去拿到本身制定的鎖(object) ,分別獲取鎖後,執行 synchronized 方法。java

    2. synchronized 拿到的鎖都是對象鎖,而不是把一段代碼、方法的鎖,多個線程就次有該方法的對象鎖。2個對象,線程獲取就是2個對象不一樣的鎖(互不影響)。ide

    3.有一種狀況就是相同的鎖,就是在該 synchronized 方法是用static關鍵字,表示鎖定 class 類,類級別的鎖獨佔l class 類。spa


    

  
  
  
  
  

thread -> B over str:b num:200 thread -> A over str:a num:1000
/** * Created by liudan on 2017/5/29. */public class MyThread2 extends Thread { private static int num = 0; public static synchronized void printNum(String str) { try { if (str.equals("a")) { num = 1000; System.err.println("thread -> A over"); Thread.sleep(1000); } else if (str.equals("b")) { num = 200; System.err.println("thread -> B over"); } System.err.println("str:" + str + "\tnum:" + num); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) { //2個不一樣的對象,只能new一次 final MyThread2 n1 = new MyThread2(); final MyThread2 n2 = new MyThread2(); Thread t1 = new Thread(new Runnable() { @Override public void run() { n1.printNum("a"); } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { n2.printNum("b"); } }); t1.start(); t2.start(); }}輸出
相關文章
相關標籤/搜索