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(); }}输出