synchronized(obj)異なるオブジェクトをロックすると

2310 ワード


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ブロックが異なるオブジェクトをロックしている場合、同期ブロックにはブロックされません.