this code reads numbers from different steam data , and outputs the whole sum. is there something wrong with this code ? how can i fix it ?
public class Thr extends Thread{
static int numThr=100, sum=0;
private int num;
private Thr(int num){this.num =num;}
public void run() {
int k = IntegerReader.get(num);
int count=0;
while(k>0) {
if(count%numThr==num) sum+=k;
count++;
k=IntegerReader.get(num);
}
}
public static void main(String[] a) throws Exception {
thr[] st =new thr[numThr];
for(int i=0; i<numThr; i++) st[i] = new Thr(i);
for(int i=0; i<numThr; i++) st[i].start();
System.out.println("sum = "+sum);
}
}
There are numerous things wrong right off the bat.
Sum is being shared between multiple threads and incremented in multiple threads meaning that you can get inconsistent values since incrementing a value isn’t an atomic operation.
The easiest fix for this is change the declaration of sum to:
private static AtomicInteger sum = new AtomicInteger(0);and add to it this way:
sum.getAndAdd(k)“numThr” is shared between multiple threads and read by multiple threads. Since numThr is not final, synchronized or volatile there isn’t any guarantee that other threads will see that its value has been initialized. numThr should be declared as
private static final int numThr=100Your
System.out.println("sum = "+sum);is going to be printed before your threads have finished executing. You need to “join” on your threads (that is, wait for them to complete) before printing sum. Add:for(int i=0; i<numThr; i++) st[i].join();before your sysout.I think you should read up on the Java Memory Model and concurrency in Java.
Here is a basic tutorial, but you really need a book on the subject:
http://docs.oracle.com/javase/tutorial/essential/concurrency/