スレッドセーフについて教えてください。
言葉の意味自体は複数のスレッドから制御が走った場合に、データの整合性が取れないものという理解をしています。
以下の、コードにおいてはCouterクラスはスレッドセーフではないという使い方で間違いないでしょうか?
例えば、synchronizedをつけるとこのクラスはスレッドセーフということなのでしょうか?
そもそも、java.util.HashMapはスレッドセーフではないというイメージがよく理解できていません。
staticなクラスのメンバがHashMapであった場合にそのメンバの挙動が保証できないということでしょうか?
Java
1public class Counter { 2 3 private int count; 4 5 public Counter() { 6 this.count = 0; 7 } 8 9 public void countUp() { 10 this.count += 1; 11 } 12 13 public int get() { 14 return this.count; 15 } 16} 17 18public class CountUpTask implements Runnable { 19 20 private Counter counter; 21 22 public CountUpTask(Counter c) { 23 this.counter = c; 24 } 25 26 @Override 27 public void run() { 28 29 for (int i = 0; i < 10000; i++) { 30 this.counter.countUp(); 31 } 32 } 33 34} 35 36public class CountUpTest1 { 37 38 public static void main(String[] args) throws InterruptedException { 39 40 Counter counter = new Counter(); 41 CountUpTask c1 = new CountUpTask(counter); 42 43 Thread t1 = new Thread(c1); 44 Thread t2 = new Thread(c1); 45 46 t1.start(); 47 t2.start(); 48 49 t1.join(); 50 t2.join(); 51 52 System.out.println(counter.get()); 53 54 } 55 56}
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/06/09 02:58