java 加锁 synchronized  经典案例

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);
	    }
}

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值