###前提・実現したいこと
synchronizedブロックを使用する箇所が、一般的な書き方ではどこになるのかが気になりました。
###該当のソースコード
Java
1public class Test { 2 public static void main(String[] args) { 3 Count count = new Count(); 4 ThreadC[] threadC = new ThreadC[10]; 5 for (int i = 0; i < 10; i++) { 6 threadC[i] = new ThreadC(count); 7 threadC[i].start(); 8 } 9 10 for (int i = 0; i < 10; i++) { 11 try { 12 threadC[i].join(); 13 } 14 catch (InterruptedException e) { 15 e.printStackTrace(); 16 } 17 } 18 19 System.out.println(count.getCount()); 20 } 21} 22 23public class Count { 24 private int count = 0; 25 26 public void add() { 27 synchronized (this) { 28 count += 10; 29 } 30 } 31 32 public int getCount() { 33 return count; 34 } 35} 36 37public class ThreadC extends Thread { 38 Count count; 39 40 public ThreadC(Count count) { 41 this.count = count; 42 } 43 44 public void run() { 45 for (int i = 0; i < 10000; i++) { 46 count.add(); 47 } 48 } 49}
Countクラスのインスタンスを渡した10個のスレッドを同期させて、全てのスレッドが終了してから結果を表示するプログラムです。
###別の書き方
ここで次のようにsynchronizedブロックを利用しても、うまく同期処理ができると思うのですが、どちらの書き方が一般的に使われているのでしょうか?使い分けなどがありましたら、そのことについても教えていただきたいです。
Java
1// synchronizedブロックを消した 2public class Count { 3 private int count = 0; 4 5 public void add() { 6 count += 10; 7 } 8 9 public int getCount() { 10 return count; 11 } 12} 13 14// synchronizedブロックを追加した 15public class ThreadC extends Thread { 16 Count count; 17 18 public ThreadC(Count count) { 19 this.count = count; 20 } 21 22 public void run() { 23 for (int i = 0; i < 10000; i++) { 24 synchronized (count) { 25 count.add(); 26 } 27 } 28 } 29}

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/11/23 09:45