M. Shaw
M. Shaw

Reputation: 1742

Java thread and synchronizedlist

I've been learning java and trying out threading and using synchronizedlist.

package Multithreading;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
public static void main(String[] args){

    List<Integer> list = Collections.synchronizedList(new ArrayList<Integer>(10));
    for(int i=0; i<10; i++){
        list.add(0);
    }
    Thread a = new Thread(new CardPicker(list));
    Thread b = new Thread(new CardPicker(list));
    Thread c = new Thread(new CardPicker(list));
    Thread d = new Thread(new CardPicker(list));
    Thread e = new Thread(new CardPicker(list));
    Thread f = new Thread(new CardPicker(list));
    Thread g = new Thread(new CardPicker(list));
    Thread h = new Thread(new CardPicker(list));
    a.start();
    b.start();
    c.start();
    d.start();
    e.start();
    f.start();
    g.start();
    h.start();
    int startTime = (int) System.currentTimeMillis();
    while((int) System.currentTimeMillis()-startTime<10000){

    }
    System.out.println(list.toString());

}
}

package Multithreading;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class CardPicker implements Runnable{

List<Integer> list;
public CardPicker(List<Integer> list2){
    this.list = list2;
}

@Override
    public void run() {
    Random rnd = new Random();
    int hold = rnd.nextInt(10);
    while(true){
        list.set(hold, list.get(hold)+1);
    }
}

}

Somehow the output gives me something like:

[13289041, 13038238, 0, 13427372, 10113077, 13023511, 15722188, 0, 12728814, 0]

[12532173, 0, 0, 12254025, 12406768, 16276566, 12638446, 16651720, 0, 0]

Where these 0s come from? Thanks

Upvotes: 1

Views: 93

Answers (1)

Braj
Braj

Reputation: 46841

Where these 0s come from?

First of all you have added 10 items in list having zero value.

At below lines you are replacing the value at a random index.

Random rnd = new Random();
int hold = rnd.nextInt(10);
while(true){
    list.set(hold, list.get(hold)+1);
}

You have 8 threads and 10 values in the list. Now for each thread a random number is generated just for single time it means in extreme case where a different random number is generated for each thread still you have 2 indexes in the list that is not replaced.

You can try it again after moving below line in while loop but still its not 100% sure that all the indexes are replaced. Its depends on the behavior of Random.

int hold = rnd.nextInt(10);

Fore more info have a look at Random#nextInt().

Upvotes: 2

Related Questions