/**
* @description 多线程锁机制
* @author: ZhaoYue
* @create: 2021-07-27 19:56
**/
public class TestClass {
public static void main(String[] args) throws InterruptedException {
A a = new A();
long start = System.currentTimeMillis();
Thread t1 = new Thread(()->{
for(int i=0;i<10000000;i++){
a.increase();
}
});
t1.start();
for(int i=0;i<10000000;i++){
a.increase();
}
//等着t1执行完毕
t1.join();
long end = System.currentTimeMillis();
System.out.println(String.format("%sms",end - start));
System.out.println(a.getNum());
}
}
class A {
int num = 0;
// 如果不加synchronized 主函数打印的a.getNum()结果会小于20000000
public synchronized void increase() {
num ++;
}
public long getNum() {
return num;
}
}
不加synchronized关键字时以上代码的运行结果:
在非静态成员方法级别上面加synchronized,锁的是当前调用这个方法的对象。(如果在静态成员方法级别上面加synchronized,锁的是类对象:类名.class)
public synchronized void increase() {
num ++;
}
以上代码等价于
public void increase() {
synchronized(this){
num ++;
}
}
synchronized底层的锁是互斥锁或叫悲观锁或同步锁。synchronized