以下のようにマルチスレッドを使ってある数に1を永遠とたすプログラムを組んだのですが、スレッドが切り替わるたびに計算結果がずれてしまいます・・・
原因と解決方法を教えてください・・・
java
1 2public class MessyCounter extends Thread { 3 4 static int counter; 5 private int id; 6 MessyCounter(int id) { 7 this.id = id; 8 } 9 public synchronized void run() { 10 while (true) { 11 System.out.println(id + ":" +counter); 12 counter++; 13 } 14 } 15 16 public static void main(String[] args) { 17 // TODO Auto-generated method stub 18 Thread t[]=new Thread[4]; 19 for(int i=0;i<4;i++){ 20 t[i]=new Thread(new MessyCounter(i)); 21 } 22 t[0].start(); 23 t[1].start(); 24 t[2].start(); 25 t[3].start(); 26 27 } 28 29} 30
回答5件
あなたの回答
tips
プレビュー