This is a very simple piece of code to add to an ArrayList with multiple threads and at the end display its contents.
Question: The while loop runs showing "Active thread count: 2" indefinitely. The first thread would obviously be the main thread. What is the second thread?
Disclaimer: I am learning about threads and while ArrayList's add method might not be thread-safe and there are alternatives that isn't the nature of the question.
public class Main {
public static void main(String[] args) {
for(int i=0;i<20;i++){
new MyThread(i);
}
while(Thread.activeCount()>1){
System.out.println("Active thread count: "+ Thread.activeCount());
}
ListClass.printList();
}
}
class MyThread extends Thread{
private int number;
public MyThread(int n)
{
number=n;
start();
}
@Override
public void run() {
ListClass.addToList(number);
}
}
class ListClass {
private static List<Integer> list = new ArrayList<>();
public static synchronized void addToList(int n){
list.add(n);
}
public static synchronized void printList(){
System.out.println(list);
}
}