synchronized作用
在并发编程中存在线程安全问题,主要原因有:
- 1.存在共享数据;
- 2.多线程共同操作共享数据;
关键字synchronized可以保证同一时刻,只有一个线程可以执行某个方法或者代码块,实现线程安全。
synchronized使用方式
分类 | 具体分类 | 被锁的对象 | 伪代码 |
方法 | 实例方法 | 类的实例对象 | public synchronized void method(){} |
静态方法 | 类对象 | public static synchronized void method(){} | |
代码块 | 实例对象 | 类的实例对象 | synchronized(this){} |
class对象 | 类对象 | synchronized(Object.class){} | |
任意实例对象 | 实例对象Object | String lock = "lock"; synchronized(lock){} |
synchronized导致死锁
死锁是两个或多个线程阻塞着等待其他处于死锁状态的线程所持有的锁。
通常发生在多个线程同时但以不同的顺序请求同一组锁的时候。
例如线程1锁住了A,同时尝试对B进行加锁,同时线程2已经锁住了B,接着尝试对A加锁,此时死锁就发生了。
package com.hexy.thread.demo;
public class DeadLockDemo {
public static void main(String[] args) {
String A = "a";
String B = "b";
Thread thread1 = new Thread(() -> {
synchronized (A) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (B) {
System.out.println("thread1 is over");
}
}
});
Thread thread2 = new Thread(() -> {
synchronized (B) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (A) {
System.out.println("thread2 is over");
}
}
});
thread1.start();
thread2.start();
}
}