// synchronize3.java class synchronize3 { public static void main(String args[]) { Shared shared = new Shared(); CustomThread6 thread1 = new CustomThread6(shared, "one"); CustomThread6 thread2 = new CustomThread6(shared, "two"); CustomThread6 thread3 = new CustomThread6(shared, "three"); CustomThread6 thread4 = new CustomThread6(shared, "four"); try { thread1.join(); thread2.join(); thread3.join(); thread4.join(); } catch(InterruptedException e) {} } } class CustomThread6 extends Thread { Shared shared; public CustomThread6(Shared shared, String string) { super(string); this.shared = shared; start(); } public void run() { shared.doWork( Thread.currentThread().getName()); } } class Shared { synchronized 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 synchronize3 Starting one Ending one Starting two Ending two Starting three Ending three Starting four Ending four