0

I am writing a program that calculate the sum of N random numbers. There are N threads, and they write the result to a common Linked List randomInts.

import java.util.LinkedList;
import java.util.Random;
import java.util.List;

class RandomInteger implements Runnable {
    public static List<Integer> randomInts = new LinkedList<Integer>();
    private static Random rand = new Random();

    public void run(){
        int tmp = rand.nextInt(11);
        System.out.println("Thread index:" + Thread.currentThread().getId() + " value: " + tmp);
        addElement(tmp);
    }

    private synchronized void addElement(int i){
        randomInts.add(i);
    }
}

class ThreadSum {
    public static void main(String[] arguments) throws InterruptedException{
        int N = 5;
        Thread[] t = new Thread[N];

        for (int i = 0 ; i < N; i++) {
            RandomInteger element = new RandomInteger();
            t[i] = new Thread(element);
            t[i].start();
        }

        for(int i = 0; i < N; i++) {
            t[i].join();
        }

        int sum = 0;
        for (Integer i:RandomInteger.randomInts) {
            sum += i;
        }
        System.out.println("Sum of elements is: " + sum);
    }   
}

When I run the program, sometimes I get the following error:

Thread index:10 value: 10
Thread index:14 value: 0
Thread index:13 value: 7
Thread index:12 value: 9
Thread index:11 value: 3
Exception in thread "main" java.lang.NullPointerException
    at java.util.LinkedList$ListItr.next(LinkedList.java:893)
    at ThreadSum.main(ThreadSum.java:36)

Other times it works:

Thread index:10 value: 4
Thread index:14 value: 6
Thread index:13 value: 5
Thread index:12 value: 4
Thread index:11 value: 10
Sum of elements is: 29

Where is the problem? How do I fix this?

Arsaceus
  • 293
  • 2
  • 19
Dzung Nguyen
  • 3,794
  • 9
  • 48
  • 86

0 Answers0