在多线程并发编程中,synchronized一直是元老级角色,很多人称呼它为重量级锁。随着Java SE1.6对synchronized的优化,在一些情况下它已经没那么重了。
synchronized应用
synchronized主要有三种应用方式:作用于实例方法、作用于静态方法以及作用于代码块。
1. 作用于实例方法:
public class SynchronizedDemo implements Runnable{
static int x = 0;
private synchronized void increase(){
for (int i = 0 ; i < 100000 ; i++){
x++;
}
}
@Override
public void run() {
increase();
}
public static void main(String[] args) throws InterruptedException {
SynchronizedDemo synchronizedInstance = new SynchronizedDemo();
//线程访问同一个对象的实例方法
Thread t1 = new Thread(synchronizedInstance);
Thread t2 = new Thread(synchronizedInstance);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(x);
}
}
输出结果:2000000
<