[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。
public class SyncTest { static Counter counter = new Counter(); // Main public static void main(String[] args){ MyThread[] threads = new MyThread[1000]; for (int i=0; i<1000; i++) { threads[i] = new MyThread(); threads[i].start(); } for (int i=0; i<1000; i++) { try { threads[i].join(); } catch (InterruptedException e) { System.out.println(e); } } System.out.println(SyncTest.counter.count); } } class MyThread extends Thread { public void run(){ SyncTest.counter.countUp(); } } //synchronized を記述しないと、結果が 995になったりしますが、 //これは、カウンター値を読み出して設定するまでの間に他のスレッドが割り込んでしまい、 //同じ値を読み出して同じ値を設定してしまうために発生します。 class Counter { int count; void countUp(){ synchronized (this) { System.out.print("["); int n = count; System.out.print("."); count = n + 1; System.out.print("]"); } } } // ちなみに、サンプルではコンストラクタは書かれてなかったが、 // 変数は、0で初期化されてるようですね。 // 危険すぎるかな。。。この書き方は。。。