1.synchronized
- 解决:原子性,内存可见性,指令重排序
- 使用场景:一读一写,多写,
- 缺点:重量
- 本质上是加锁,针对某个对象加锁,只有一个线程能获取到该对象的锁,其他线程只能阻塞等待
- 实际上就是把并发变成了串行,除去了抢占式执行带来的随机性
2.synchronize(关键字) 监视器锁(atm取钱)
- 功能:保证操作的原子性,禁止指令重排序,保证内存可见性
3.2修饰一个方法
相当于加了LOCK,UNLOCK
synchronized public void increase(){
count++;
}
4修饰一个代码块
public void increase() {
synchronized (this) {
count++;
}
}
Thread t2 = new Thread() {
@Override
public void run() {
for (int i = 0; i < 50000; i++) {
synchronized(counter){
counter.increase();
}
}
}
};
5嵌套加锁
- synchronized内部进行了特殊处理,可重入锁。
/**
* User:yang
*/
class Counter {
public static int count = 0;
// public void increase(){
// count++;
//
// }
synchronized void increase() {
count++;
}
// public void increase() {
// synchronized (this) {
// count++;
// }
// }
}
public class ThreadDemo12 {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread t1 = new Thread() {
@Override
public void run() {
for (int i = 0; i < 50000; i++) {
synchronized (counter) {
counter.increase();
}
}
}
};
Thread t2 = new Thread() {
@Override
public void run() {
for (int i = 0; i < 50000; i++) {
synchronized (counter) {
counter.increase();
}
}
}
};
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(counter.count);
}
}