多个线程多个锁
1.多个线程,每个线程都可以去拿到自己制定的锁(object) ,分别获取锁后,执行 synchronized 方法。
2. synchronized 拿到的锁都是对象锁,而不是把一段代码、方法的锁,多个线程就次有该方法的对象锁。2个对象,线程获取就是2个对象不同的锁(互不影响)。
3.有一种情况就是相同的锁,就是在该 synchronized 方法是用static关键字,表示锁定 class 类,类级别的锁独占l class 类。
/*** 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 + " num:" + 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() {@Overridepublic void run() {n1.printNum("a");}});Thread t2 = new Thread(new Runnable() {@Overridepublic void run() {n2.printNum("b");}});t1.start();t2.start();}}输出thread -> B over str:b num:200 thread -> A over str:a num:1000