synchronized (obj) 锁住不同的对象的话

 

Obj 

package com.james.thread.sync;

public class SyncObject {

	byte[] lock1 = new byte[0];
	byte[] lock2 = new byte[0];

	int i = 1;

	public int minus() {
		try {
		
		synchronized (lock1) {
			System.out.println("minus in");
			Thread.currentThread().sleep(300);
				i--;
				System.out.println("minus " + i);
			
			
		}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return i;
	}

	public int add() {
		
		synchronized (lock2) {
			try {
				System.out.println("add in");
				Thread.currentThread().sleep(5);
				i++;
				System.out.println("add " + i);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return i;
		}

	}
	
	public synchronized int minus2() {
			i--;
			System.out.println("minus "+ i);
			return i;

	}

	public synchronized int add2() {
			i++;
			System.out.println("add "+ i);
			return i;

	}

}

 

Test

package com.james.thread.sync;

public class Test {

	public static void main(String[] args) throws InterruptedException {
		SyncObject obj = new SyncObject ();
		Thread t =null;
		for(int i =1;i<3;i++){
			t = new Thread(new TestThread (i,obj));
			t.start();
		}
//		Thread.currentThread().sleep(500);
//		System.out.println(obj.i);
	}

	static class TestThread implements Runnable {
		private int flag = 100;
		private SyncObject obj;
		public TestThread(int flag,SyncObject obj){
			this.flag = flag;
			this.obj = obj;
		}
		public void run (){
			if(flag %2 == 0){
				obj.add();
			}else{
				obj.minus();
			}
		}
	}
}

 

输出

minus in
add in
add 2
minus 1

 

说明 synchronized块锁住不同对象的时候,同步块里是不会阻塞的。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值