Tank Vvv Tank Vvv - 21 days ago 5
Java Question

Java Thread Output data to Collection getting wrong results

I wrote a small program for testing java's Thread.
The problem is that I cannot get results as I predicted: 100 records every time.
I got random number of records. and after I remove the comment of this line:

//System.out.println(name + " Completed.");

I got 100 records as predicted every time.
In other words, I add a System.out.println(), everything works perfect.
Is that the java's bug or something I didn't noticed?

MyThread.java

public class MyThread extends Thread {

@Override
public void run() {

String name = Thread.currentThread().getName();

for (int i = 1; i <= 10; i++) {
if (i == 10) {
//System.out.println(name + " Completed.");
TestThread.al.add(name);
}
}

}

}


TestThread.java

import java.util.ArrayList;

public class TestThread {

public static ArrayList<String> al = new ArrayList<String>();

public static void main(String[] args) throws Exception {

ArrayList<MyThread> mt = new ArrayList<MyThread>();

//set
for (int i = 0; i < 100; i++) {
mt.add(new MyThread());
mt.get(i).setName("Worker " + (i + 1));
}

//start
for (int i = 0; i < 100; i++) {
mt.get(i).start();
}

//end
for (int i = 0; i < 100; i++) {
mt.get(i).join();
}

//result
for (int i = 0; i < al.size(); i++) {
System.out.println("Rank " + (i+1) + " : " + al.get(i));
}

}

}

Answer

the ArrayList is not thread-safe, maybe there exist a case: the two threads write data to the same positon of the arrayList ,you can use Vector instead for it is thread-safe.

for more information about thread-safe come here