synchronized(static XX)の失効例

3345 ワード

import java.awt.AWTException;
import java.awt.Robot;


public class TestThread1 implements Runnable {
	
	private static String name;
	
	public TestThread1(String name){
		this.name=name;
	}

	@Override
	public void run() {
		synchronized(name){
			for(int i=0;i<10;i++){
				try {
					Robot r = new Robot();
					r.delay(1000);
				} catch (AWTException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println(Thread.currentThread().getName()+" "+name+i);
			}
		}
	}
	
	public static void main(String args[]){
		TestThread1 th1 = new TestThread1("A");
		Thread t1 = new Thread(th1);
		t1.start();

		TestThread1 th2 = new TestThread1("B");
		Thread t2 = new Thread(th2);
		t2.start();
		
/*		Robot r;
		try {
			r = new Robot();
			r.delay(2000);
		} catch (AWTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		TestThread1.name="C";*/
		TestThread1 th3 = new TestThread1("D");
		Thread t3 = new Thread(th3);
		t3.start();
	}

}

結果:
Thread-0 D0
Thread-1 D0
Thread-1 D1
Thread-0 D1
Thread-0 D2
Thread-1 D2
Thread-1 D3
Thread-0 D3
Thread-1 D4
Thread-0 D4
Thread-1 D5
Thread-0 D5
Thread-1 D6
Thread-0 D6
Thread-1 D7
Thread-0 D7
Thread-0 D8
Thread-1 D8
Thread-1 D9
Thread-0 D9
Thread-2 D0
Thread-2 D1
Thread-2 D2
Thread-2 D3
Thread-2 D4
Thread-2 D5
Thread-2 D6
Thread-2 D7
Thread-2 D8
Thread-2 D9
 
スレッド内のstaticの変数値を変更するスレッドが介入を開始するとsynchronized(static XX)は失効することが分かった.
次の状況は失効せず、奇妙だ.
import java.awt.AWTException;
import java.awt.Robot;


public class TestThread1 implements Runnable {
	
	private static String name;
	
	public TestThread1(String name){
		this.name=name;
	}

	@Override
	public void run() {
		synchronized(name){
			for(int i=0;i<10;i++){
				try {
					Robot r = new Robot();
					r.delay(1000);
				} catch (AWTException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println(Thread.currentThread().getName()+" "+name+i);
			}
		}
	}
	
	public static void main(String args[]){
		TestThread1 th1 = new TestThread1("A");
		Thread t1 = new Thread(th1);
		t1.start();

		TestThread1 th2 = new TestThread1("B");
		Thread t2 = new Thread(th2);
		t2.start();
		

	}

}

結果:
Thread-0 B0
Thread-0 B1
Thread-0 B2
Thread-0 B3
Thread-0 B4
Thread-0 B5
Thread-0 B6
Thread-0 B7
Thread-0 B8
Thread-0 B9
Thread-1 B0
Thread-1 B1
Thread-1 B2
Thread-1 B3
Thread-1 B4
Thread-1 B5
Thread-1 B6
Thread-1 B7
Thread-1 B8
Thread-1 B9