dfetter88
dfetter88

Reputation: 5391

Help beginner understand threads

I have an array of MyThreads (seen below) running, but they produce incorrect results. What is the problem here?

import java.util.*;
class MyThread extends Thread {
  public static long N;
  public static long sum = 0;
  synchronized public void inc() {
    sum++;
  }
  public void run() {
    for (long i = 0; i < N; i++) {
      inc();
    }
  }
  public MyThread(long num) {
    N = num;
  }
}

My guess is that the threads are interrupting each other, causing the incorrect results, but I don't understand where or how.

Upvotes: 0

Views: 128

Answers (1)

casablanca
casablanca

Reputation: 70701

First, it appears that N is a per-thread iteration count, so it shouldn't be static.

Second, since sum is a static member, your inc method should also be static, otherwise you won't be synchronizing on the static fields of the class.

Upvotes: 3

Related Questions