I am confused -- Will this code always work?

Posted by Shekhar on Stack Overflow See other posts from Stack Overflow or by Shekhar
Published on 2010-04-30T09:15:43Z Indexed on 2010/04/30 9:17 UTC
Read the original article Hit count: 310

Filed under:
|
|

Hello,

I have written this piece of code

public class Test{

public static void main(String[] args) {

    List<Integer> list = new ArrayList<Integer>();

    for(int i = 1;i<= 4;i++){
        new Thread(new TestTask(i, list)).start();
    }

    while(list.size() != 4){
        // this while loop required so that all threads complete their work
    }

    System.out.println("List "+list);
}

}

class TestTask implements Runnable{

private int sequence;
private List<Integer> list;

public TestTask(int sequence, List<Integer> list) {
    this.sequence = sequence;
    this.list = list;
}

@Override
public void run() {
    list.add(sequence);
}

}

This code works and prints all the four elements of list on my machine.

My question is that will this code always work. I think there might be a issue in this code

when two/or more threads add element to this list at the same point. In that case it while

loop will never end and code will fail.

Can anybody suggest a better way to do this? I am not very good at multithreading and don't

know which concurrent collection i can use?

Thanks

Shekhar

© Stack Overflow or respective owner

Related posts about java

Related posts about threads