The first code does not always show the sum to be 1000, so I figured a way around to fix the problem but why does not the first code work? The results are highly inconsistent and I know that using synchronized does not serve any purpose in this case, but I was just trying.
class Thread1 extends Thread{
int[] count;
int[] event;
Thread1(int[] event, int[] count){
this.event=event;
this.count=count;
}
public void run(){
for(int i=0; i<500; i++){
int x = event[i];
synchronized (count){
count[x]++;
}
}
}
}
class Thread2 extends Thread{
int[] count;
int[] event;
Thread2(int[] event, int[] count){
this.event=event;
this.count=count;
}
public void run(){
for(int i=500; i<1000; i++){
int x = event[i];
synchronized (count){
count[x]++;
}
}
}
}
public class Learning {
public static void main(String[] args) {
Random random = new Random();
int[] event = new int[1000];
for(int i=0; i<event.length; i++){
event[i] = random.nextInt(3);
}
Thread1 a = new Thread1(event, new int[3]);
Thread2 b = new Thread2(event, new int[3]);
a.start();
b.start();
int second = a.count[1]+b.count[1];
int third = a.count[2]+b.count[2];
int first = a.count[0]+b.count[0];
System.out.println(first);
System.out.println(second);
System.out.println(third);
System.out.println("SUM--> "+(first+second+third));
}
}
WORKS HERE:
DOES NOT WORK HERE
The code sometimes shows a total of 1000 entries, sometimes doesn't. I don't feel there is any need to synchronize as no common resource is being accesed.