// synchronize1.java class synchronize1 { public static void main(String args[]) { Shared shared = new Shared(); CustomThread4 thread1 = new CustomThread4(shared, "one"); CustomThread4 thread2 = new CustomThread4(shared, "two"); CustomThread4 thread3 = new CustomThread4(shared, "three"); CustomThread4 thread4 = new CustomThread4(shared, "four"); try { thread1.join(); thread2.join(); thread3.join(); thread4.join(); } catch(InterruptedException e) {} } } class CustomThread4 extends Thread { Shared shared; public CustomThread4(Shared shared, String string) { super(string); this.shared = shared; start(); } public void run() { shared.doWork( Thread.currentThread().getName()); } } class Shared { void doWork(String string) { System.out.println("Starting " + string); try { Thread.sleep((long) (Math.random() * 500)); } catch (InterruptedException e) {} System.out.println("Ending " + string); } }
これを実行すると, % java synchronize1 Starting one Starting two Starting three Starting four Ending one Ending two Ending four Ending threeという形で,Endingの順番がStartingの順番と 異なる.