java 中synchronized 关键字的使用
文章导航
- 对象锁两种方式
- 1.方法名前加 synchronized 关键字
- 2.方法中加 synchronized(this){…}
- 类锁三种方式
- 1.静态方法名前加synchronized关键字
- 2.方法中加 synchronized(xxx.class){…}
- 3.静态方法块中加synchronized关键字
- 下一篇 会继续更新synchronized关键字实现原理,敬请期待
一、对象锁
对象锁顾名思义,就是指锁的作用域是java中的对象,每创建一个对象,会同时创建锁,对象和对象间的锁互补干扰,独立起作用。
1.方法名前加 synchronized 关键字
/**
* 方法名前加 synchronized 关键字
*/
public synchronized void test01() {
System.out.println("test01 当前线程:" + Thread.currentThread().getName() + ",锁定中。。。");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("test01 当前线程:" + Thread.currentThread().getName() + ",锁定结束。。。");
}
2.方法中加 synchronized(this){…}
public void test02() {
synchronized (this) {
System.out.println("test 当前线程:" + Thread.currentThread().getName() + ",锁定中。。。");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("test 当前线程:" + Thread.currentThread().getName() + ",锁定结束。。。");
}
}
二、类锁三种方式
类锁是指锁加到通过类实例化的所有对象上,对象间共用一把锁,某一线程获取锁后,其他线程访问通过该类实例的对象时将等待,锁被释放后拿到锁继续执行任务。
1.静态方法名前加synchronized关键字
/**
* 静态方法名前加synchronized关键字
*/
public synchronized static void test03() {
System.out.println("test01 当前线程:" + Thread.currentThread().getName() + ",锁定中。。。");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("test01 当前线程:" + Thread.currentThread().getName() + ",锁定结束。。。");
}
2.方法中加 synchronized(xxx.class){…}
/**
* 方法中加 synchronized(xxx.class){...}
*/
public static void test04() {
synchronized (DemoClass.class) {
System.out.println("test01 当前线程:" + Thread.currentThread().getName() + ",锁定中。。。");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("test01 当前线程:" + Thread.currentThread().getName() + ",锁定结束。。。");
}
}
3.静态方法块中加synchronized关键字
static {
synchronized (DemoClass.class) {
System.out.println("static 当前线程:" + Thread.currentThread().getName() + ",锁定中。。。");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("static 当前线程:" + Thread.currentThread().getName() + ",锁定结束。。。");
}
}
欢迎留言,大家一块学习,共同进步!