java 加锁 synchronized 经典案例
案例一
public class synchronizedTest implements Runnable {
//共享资源
static int i =0;
/**
* synchronized 修饰实例方法
*/
public void increase(){
i++;
}
@Override
public synchronized void run(){
for (int j =0 ; j<10000;j++){
increase();
}
}
/**
* 1、join 加和不加的区别
* 2、 synchronized 和 synchronized static 的区别
* 3、join(t1/t2) 的顺序区别
*/
public static void main(String[] args) throws InterruptedException {
synchronizedTest test = new synchronizedTest();
Thread t1 = new Thread(test);
Thread t2 = new Thread(test);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(i);
}
}
案例二
public class synchronizedTest3 implements Runnable{
//共享资源
static int i =0;
/**
* synchronized 修饰实例方法
*/
public static synchronized void increase(){
i++;
}
@Override
public void run(){
for (int j =0 ; j<10000;j++){
increase();
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new synchronizedTest3());
Thread t2 = new Thread(new synchronizedTest3());
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(i);
}
}
案列三
public class synchronizedTest4 implements Runnable{
static AtomicBoolean instance=new AtomicBoolean();
static int i=0;
public void increase(){
synchronized(instance){
for(int j=0;j<10000;j++){
i++;
}
}
}
@Override
public void run() {
//省略其他耗时操作....
//使用同步代码块对变量i进行同步操作,锁对象为instance
increase();
}
public static void main(String[] args) throws InterruptedException {
Thread t1=new Thread(new synchronizedTest4());
Thread t2=new Thread(new synchronizedTest4());
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(i);
}
}