1、作用
synchronized是java的一个关键字,是JVM层面提供解决并发问题的简单常用手段。可以保证同一时刻仅一个线程运行指定代码块或方法。即为所谓的加锁操作。
2、概述
加锁操作是依赖于对象的,java的任何对象都可以用于锁住代码块或方法。每个对象里面都存有一个“锁”对象,用于标识哪个线程获取了此“锁”对象,一旦某线程获取,其它线程便只能等待释放。
互斥性:共用同一个锁对象,线程间执行互斥。如上图,inst对象内部的锁信息仅能记录一个线程信息,当记录thread1时,thread2就进不来。
可重入性:当同一个类多个同步方法相互调用时,锁对象信息记录的是同一个线程,所以重入不会被锁,如下图。
3、用法
synchronized有三种用法
- synchronized修饰普通方法,锁对象即为本类的实例。
- synchronized修饰代码块,锁对象即为小括号中的实例。
- synchronized修饰静态方法,锁对象即为本类class实例。
4、案例演示
①synchronized修饰普通方法
/*代码*/
public class Demo implements Runnable {
public synchronized void exeMethod() {
System.out.println(Thread.currentThread().getName()+": method start");
try {
Thread.sleep(3000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+": method end");
}
@Override
public void run() {
exeMethod();
}
public static void main(String[] args) {
/**
* 因为synchronized锁的是当前对象,所以需要使用同一个对象启动线程
*/
Demo demo = new Demo();
new Thread(demo).start();
new Thread(demo).start();
}
}
/*运行结果*/
Thread-0: method start
Thread-0: method end
Thread-1: method start
Thread-1: method end
②synchronized修饰代码块
/*代码*/
public class Demo implements Runnable {
public void exeMethod() {
//字符串"lock"充当锁对象,多个线程用的是一个字符串常量对象"lock"
synchronized ("lock"){
System.out.println(Thread.currentThread().getName()+": method start");
try {
Thread.sleep(3000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+": method end");
}
}
@Override
public void run() {
exeMethod();
}
public static void main(String[] args) {
/**
* 因为synchronized锁的是同一个字符串对象"lock",所以无需使用同一个对象启动线程
*/
new Thread(new Demo()).start();
new Thread(new Demo()).start();
}
}
/*运行结果*/
Thread-0: method start
Thread-0: method end
Thread-1: method start
Thread-1: method end
③synchronized修饰静态方法
/*代码*/
public class Demo {
//synchronized修饰静态方法,锁对象为本类的class对象
public synchronized static void method1() {
System.out.println(Thread.currentThread().getName()+": method1 start");
try {
Thread.sleep(3000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+": method1 end");
}
public void method2(){
//手动获取本类的class对象作为锁对象,效果和synchronized修饰静态方法相同
synchronized (this.getClass()){
System.out.println(Thread.currentThread().getName()+": method2 start");
try {
Thread.sleep(3000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+": method2 end");
}
}
public static void main(String[] args) {
new Thread(()->{
Demo.method1();
}).start();
new Thread(()->{
new Demo().method2();
}).start();
}
}
/*运行结果*/
Thread-0: method1 start
Thread-0: method1 end
Thread-1: method2 start
Thread-1: method2 end