概述
synchronized是java的关键字,它的作用是加同步锁,即被synchronized修饰的部分同一时间只允许一个线程访问,它的使用场景有如下几种:
- 修饰普通方法:对当前对象实例加锁,调用该方法需要获得当前对象实例的锁
- 修饰静态方法:对当前类加锁,会对该类的所有实例加锁,因为静态方法不属于任何一个实例对 象,是属于类成员。所以当线程A访问调用一个实例对象的synchronized方法,线程B调用这个实例对象的静态synchronized方法是允许的
- 修饰代码块:对指定的对象加锁,可以指定变量,也可以指定类,指定变量是需要获得该变量对应类的实例锁,由于基本类型不是对象,所以synchronized不可以修饰基本类型变量;指定类是需要获得当前类加锁
说明: synchronized的作用域为整个JVM虚拟机下,只要在同一JVM虚拟机下,synchronized对于任何访问都能起作用,所以在单体架构下,synchronized能保证线程安全,但是在分布式架构,synchronized并不能保证线程安全。
下面我们对各种场景synchronized使用效果进行验证
测试类:
public class Ticket {
private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss.SSS");
private static Integer number = 100;
private String ticketId;
private static final Object obj = new Object();
private Object lock;
public Object getLock() {
return lock;
}
public void setLock(Object lock) {
this.lock = lock;
}
public String getTicketId() {
return ticketId;
}
/**
* 普通 synchronized方法 (获取到该对象实例即获取到synchronized锁)
*/
public synchronized Object buyTicket(Integer count, Long id) {
for (int i = 0; i < count; i++) {
method1(id);
number--;
}
return number;
}
/**
* 静态synchronized方法 (获取到该类即获取到synchronized锁)
*/
public static synchronized Object calcTotal(Integer count, Long id, Integer price) {
Integer total = 0;
for (int i = 0; i < count; i++) {
method2(id, price, total);
}
return total;
}
/**
* synchronized修饰普通对象(获取到该对象的实例即获取到锁)
*/
public Object buyTicket1(Integer count, Long id) {
synchronized (lock) {
for (int i = 0; i < count; i++) {
method1(id);
number--;
}
}
return number;
}
/**
* synchronized修饰类(获取到该类即获取到锁)
*/
public Object calcTotal1(Integer count, Long id, Integer price) {
Integer total = 0;
synchronized (Ticket.class) {
for (int i = 0; i < count; i++) {
method2(id, price, total);
}
}
return total;
}
private void method1(Long id) {
try {
System.out.println("Thread-" + id + "暂停1秒。。。。。。");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.ticketId = UUID.randomUUID().toString().replace("-", "");
System.out.println(simpleDateFormat.format(new Date()) + " Thread-" + id + ": number = "
+ number + ", ticketId = " + ticketId);
}
private static void method2(Long id, Integer price, Integer total) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss.SSS");
try {
System.out.println("Thread-" + id + "暂停1秒。。。。。。");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Integer num = (int)(Math.random()*10 + 1);
total += total + num * price;
System.out.println(simpleDateFormat.format(new Date()) + " Thread-" + id + ": number = "
+ number + ", total = " + total);
number -= num;
}
}
修饰普通方法
1. 线程A,B调用相同对象的普通synchronized方法
测试代码:
public class threadSynTest {
private Ticket ticket;
private static threadSynTest threadSynTest = new threadSynTest();
public static void main(String[] args) throws Exception{
threadSynTest.ticket = new Ticket(); // 给ticket创建新对象
MyRunnable myRunnable1 = threadSynTest.new MyRunnable();
MyRunnable myRunnable2 = threadSynTest.new MyRunnable();
Thread A = new Thread(myRunnable1);
Thread B = new Thread(myRunnable2);
A.start();
Thread.sleep(1000); //延时1s后再启动线程B,保证线程A先获取到锁
B.start();
}
/**
* 线程1 测试普通synchronized方法
*/
class MyRunnable implements Runnable {
private Integer count = 5;
@Override
public void run() {
Long threadId = Thread.currentThread().getId();
//获取ticket,若为空则创建新对象
Ticket ticket1 = ticket == null ? new Ticket() : ticket;
System.out.println("Thread-" + threadId + " start: " + ticket1.toString());
//调用Ticket普通synchronized方法
Object obj = ticket1.buyTicket(count, threadId);
System.out.println("Thread-" + threadId + " end: " + obj.toString());
}
}
}
运行结果
2. 线程A,B调用不同对象的普通synchronized方法
测试代码:
public class threadSynTest {
private Ticket ticket;
private static threadSynTest threadSynTest = new threadSynTest();
public static void main(String[] args) throws Exception{
MyRunnable myRunnable1 = threadSynTest.new MyRunnable();
MyRunnable myRunnable2 = threadSynTest.new MyRunnable();
Thread A = new Thread(myRunnable1);
Thread B = new Thread(myRunnable2);
A.start();
Thread.sleep(1000); //延时1s后再启动线程B,保证线程A先获取到锁
B.start();
}
/**
* 线程1 测试普通synchronized方法
*/
class MyRunnable implements Runnable {
private Integer count = 5;
@Override
public void run() {
Long threadId = Thread.currentThread().getId();
//获取ticket,若为空则创建新对象
Ticket ticket1 = ticket == null ? new Ticket() : ticket;;
System.out.println("Thread-" + threadId + " start: " + ticket1.toString());
//调用Ticket普通synchronized方法
Object obj = ticket1.buyTicket(count, threadId);
System.out.println("Thread-" + threadId + " end: " + obj.toString());
}
}
}
运行结果
结论:
根据上述两段代码结果显示,当线程A,B获取同一实例时,A先获取到实例,A先执行普通synchronized方法,B被阻塞中,待A执行完释放锁,B才开始执行方法;当线程A,B获取不同的实例,即使A先获取到实例,也不能阻塞B线程执行synchronized方法,所以当synchronized修饰普通方法时,只有访问同一类实例才能保证线程安全,即synchronized修饰普通方法时,只有在同一实例下,synchronized关键字才能发挥同步锁作用
说明:在spring框架中,对于被spring容器注册为bean的类来说,由于spring bean默认为单例模式,所以bean中普通方法被synchronized修饰基本都能够发挥synchronized线程同步的作用
修饰静态方法
1. 线程A,B调用相同对象的静态synchronized方法
测试代码:
public class threadSynTest {
private Ticket ticket;
private static threadSynTest threadSynTest = new threadSynTest();
public static void main(String[] args) throws Exception{
threadSynTest.ticket = new Ticket(); // 给ticket创建新对象
MyRunnable1 myRunnable1 = threadSynTest.new MyRunnable1();
MyRunnable1 myRunnable2 = threadSynTest.new MyRunnable1();
Thread A = new Thread(myRunnable1);
Thread B = new Thread(myRunnable2);
A.start();
Thread.sleep(1000); // 延时1s后再启动线程B,保证线程A先获取到锁
B.start();
}
/**
* 线程2 测试静态synchronized方法
*/
class MyRunnable1 implements Runnable {
private Integer count = 5;
private Integer price = 20;
@Override
public void run() {
Long threadId = Thread.currentThread().getId();
// 获取ticket,若为空则创建新对象
Ticket ticket1 = ticket == null ? new Ticket() : ticket;
System.out.println("Thread-" + threadId + " start: " + ticket1.toString());
//调用Ticket静态synchronized方法
Object obj = ticket1.calcTotal(count, threadId, price);
System.out.println("Thread-" + threadId + " end: " + obj.toString());
}
}
}
运行结果:
2. 线程A,B调用不同对象的静态synchronized方法
测试代码:
public class threadSynTest {
private Ticket ticket;
private static threadSynTest threadSynTest = new threadSynTest();
public static void main(String[] args) throws Exception{
MyRunnable1 myRunnable1 = threadSynTest.new MyRunnable1();
MyRunnable1 myRunnable2 = threadSynTest.new MyRunnable1();
Thread A = new Thread(myRunnable1);
Thread B = new Thread(myRunnable2);
A.start();
Thread.sleep(1000); // 延时1s后再启动线程B,保证线程A先获取到锁
B.start();
}
/**
* 线程2 测试静态synchronized方法
*/
class MyRunnable1 implements Runnable {
private Integer count = 5;
private Integer price = 20;
@Override
public void run() {
Long threadId = Thread.currentThread().getId();
// 获取ticket,若为空则创建新对象
Ticket ticket1 = ticket == null ? new Ticket() : ticket;
System.out.println("Thread-" + threadId + " start: " + ticket1.toString());
//调用Ticket静态synchronized方法
Object obj = ticket1.calcTotal(count, threadId, price);
System.out.println("Thread-" + threadId + " end: " + obj.toString());
}
}
}
运行结果
结论:
根据上述代码运行结果显示,不管线程A,B访问类不管是不是同一对象实例,调用其静态synchronized方法,总是是先调用方获取到锁并执行静态synchronized方法,后调用方被阻塞;即synchronized修饰静态方法,会对该类的所有实例加同步锁
修饰普通对象
1. 线程A,B获取到相同的对象实例并执行同步代码块
测试代码:
public class threadSynTest {
private Ticket ticket;
private static threadSynTest threadSynTest = new threadSynTest();
public static void main(String[] args) throws Exception{
threadSynTest.ticket = new Ticket(); //给ticket创建新对象
threadSynTest.ticket.setLock(new Object()); //给ticket的lock变量创建新对象
MyRunnable2 myRunnable1 = threadSynTest.new MyRunnable2();
MyRunnable2 myRunnable2 = threadSynTest.new MyRunnable2();
Thread A = new Thread(myRunnable1);
Thread B = new Thread(myRunnable2);
A.start();
Thread.sleep(1000); // 延时1s后再启动线程B,保证线程A先获取到锁
B.start();
}
/**
* 线程3 测试synchronized修饰普通变量
*/
class MyRunnable2 implements Runnable {
private Integer count = 5;
@Override
public void run() {
Long threadId = Thread.currentThread().getId();
if (threadSynTest.ticket.getLock() == null) {
threadSynTest.ticket.setLock(new Object());
}
System.out.println("Thread-" + threadId + " start: " + threadSynTest.ticket.getLock().toString());
Object obj = ticket.buyTicket1(count, threadId);
System.out.println("Thread-" + threadId + " end: " + obj.toString());
}
}
}
运行结果:
2. 线程A,B获取到不同的对象实例并调用同步代码块
测试代码:
public class threadSynTest {
private Ticket ticket;
private static threadSynTest threadSynTest = new threadSynTest();
public static void main(String[] args) throws Exception{
threadSynTest.ticket = new Ticket(); //给ticket创建新对象
MyRunnable2 myRunnable1 = threadSynTest.new MyRunnable2();
MyRunnable2 myRunnable2 = threadSynTest.new MyRunnable2();
Thread A = new Thread(myRunnable1);
Thread B = new Thread(myRunnable2);
A.start();
Thread.sleep(1000); // 延时1s后再启动线程B,保证线程A先获取到锁
//线程A执行后再给ticket的lock变量创建新对象,保证A,b获取的不是同一lock实例
threadSynTest.ticket.setLock(new Object());
B.start();
}
/**
* 线程3 测试synchronized修饰普通变量
*/
class MyRunnable2 implements Runnable {
private Integer count = 5;
@Override
public void run() {
Long threadId = Thread.currentThread().getId();
if (threadSynTest.ticket.getLock() == null) {
threadSynTest.ticket.setLock(new Object());
}
System.out.println("Thread-" + threadId + " start: " + threadSynTest.ticket.getLock().toString());
Object obj = ticket.buyTicket1(count, threadId);
System.out.println("Thread-" + threadId + " end: " + obj.toString());
}
}
}
运行结果
结论:
根据上述两段代码结果显示,当线程A,B获取到的被synchronized修饰的对象的是同一实例,A先获取到对象实例,A先执行synchronized代码块,B被阻塞中,待A执行完释放锁,B才开始执行方法;当线程A,B获取到的被synchronized修饰的对象的是不同实例时,即使A先获取到实例,也不能阻塞B线程执行synchronized代码块,其作用和synchronized修饰普通方法类似;即synchronized修饰普通对象时,只有在获取到该对象同一实例下,synchronized关键字才能发挥同步锁作用
说明:由于不同的实例可以有相同的引用,所以在上述情况下,当线程A,B是访问的不同实例的synchronized修饰普通对象的代码块,只要这两实例引用的是同一个被synchronized修饰对象的实例,synchronized同样能发挥同步锁作用
修饰类
1. 线程A,B获取到相同的类对象实例并执行同步代码块
测试代码:
public class threadSynTest {
private Ticket ticket;
private static threadSynTest threadSynTest = new threadSynTest();
public static void main(String[] args) throws Exception{
threadSynTest.ticket = new Ticket(); //给ticket创建新对象
MyRunnable3 myRunnable1 = threadSynTest.new MyRunnable3();
MyRunnable3 myRunnable2 = threadSynTest.new MyRunnable3();
Thread A = new Thread(myRunnable1);
Thread B = new Thread(myRunnable2);
A.start();
Thread.sleep(1000); // 延时1s后再启动线程B,保证线程A先获取到锁
B.start();
}
/**
* 线程4 测试synchronized修饰普通变量
*/
class MyRunnable3 implements Runnable {
private Integer count = 5;
private Integer price = 20;
@Override
public void run() {
Long threadId = Thread.currentThread().getId();
// 获取ticket,若为空则创建新对象
Ticket ticket1 = ticket == null ? new Ticket() : ticket;
System.out.println("Thread-" + threadId + " start: " + ticket1.toString());
Object obj = ticket1.calcTotal1(count, threadId, price);
System.out.println("Thread-" + threadId + " end: " + obj.toString());
}
}
}
运行结果:
2. 线程A,B获取到不同的类对象实例并调用同步代码块
测试代码:
public class threadSynTest {
private Ticket ticket;
private static threadSynTest threadSynTest = new threadSynTest();
public static void main(String[] args) throws Exception{
MyRunnable3 myRunnable1 = threadSynTest.new MyRunnable3();
MyRunnable3 myRunnable2 = threadSynTest.new MyRunnable3();
Thread A = new Thread(myRunnable1);
Thread B = new Thread(myRunnable2);
A.start();
Thread.sleep(1000); // 延时1s后再启动线程B,保证线程A先获取到锁
B.start();
}
/**
* 线程4 测试synchronized修饰普通变量
*/
class MyRunnable3 implements Runnable {
private Integer count = 5;
private Integer price = 20;
@Override
public void run() {
Long threadId = Thread.currentThread().getId();
// 获取ticket,若为空则创建新对象
Ticket ticket1 = ticket == null ? new Ticket() : ticket;
System.out.println("Thread-" + threadId + " start: " + ticket1.toString());
Object obj = ticket1.calcTotal1(count, threadId, price);
System.out.println("Thread-" + threadId + " end: " + obj.toString());
}
}
}
运行结果
结论:
根据上述代码运行结果显示,不管线程A,B访问类不管是不是同一对象实例,调用synchronized修饰该类的代码块,总是是先调用方获取到锁并执行被synchronized修饰的代码块,后调用方被阻塞,作用和synchronized修饰静态方法类似;即synchronized修饰静态方法,会对该类的所有实例加同步锁