一、锁对象及 synchronized 的使用
synchronized 通过互斥锁(Mutex Lock)来实现,同一时刻,只有获得锁的线程才可以执行锁内的代码。
锁对象分为两种:
实例对象(一个类有多个)和 Class 对象(一个类只有一个)。
不同锁对象之间的代码执行互不干扰,同一个类中加锁方法与不加锁方法执行互不干扰。
使用 synchronized 有以下种方式:
修饰普通方法,锁当前实例对象。
修饰静态方法,锁当前类的 Class 对象。
修饰代码块,锁括号中的对象(实例对象或 Class 对象)。
示例:
class SynchronizedDemo { // 类锁(修饰静态方法:锁当前类的 Class 对象。) public static synchronized void inStaticMethod() { for (int i = 0; i < 10; i++) { System.out.println("aaa"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } // 类锁(修饰代码块,锁括号中的 Class 对象) public static void inStaticMethodLockClassObj() { synchronized(SynchronizedDemo.class){ for (int i = 0; i < 10; i++) { System.out.println("aaa"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } // 对象锁(修饰普通方法:锁当前实例对象) public synchronized void inNormalMethod() { for (int i = 0; i < 10; i++) { System.out.println("bbb"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } // 对象锁(修饰代码块:锁括号中的实例对象) public void bb() { synchronized(this){ for (int i = 0; i < 10; i++) { System.out.println("bbb"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } // 无锁 public void cc() { for (int i = 0; i < 10; i++) { System.out.println("ccc"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }