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块锁住不同对象的时候,同步块里是不会阻塞的。

猜你喜欢

转载自k1280000.iteye.com/blog/2037231