0

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);
        }
    }
alwayscurious
  • 1,155
  • 1
  • 8
  • 18
  • 4
    Java itself also starts some threads (I am actually surprised you only have the main thread and 1 other). Note that this is **not** how you should wait for completion of threads. – Mark Rotteveel Aug 31 '17 at 10:16
  • Ah I see. I hope I can ask this as part of the same question: what other threads does java start itself - for what purpose? – alwayscurious Aug 31 '17 at 10:18
  • Try adding `Thread.getAllStackTraces().keySet().forEach(System.out::println);`which lists all threads. Will show you a number of "infrastructure" threads for the JVM. – Henrik Aasted Sørensen Aug 31 '17 at 10:19
  • @JonJavaK The JVM will start threads of its own if/as needed. My guess is that their purpose may depend on the particular JVM implementation. For example, when using AWT, there'll be a thread called `AWT-EventQueue` or something along those lines. Others might be for GC purposes, etc. – code_dredd Aug 31 '17 at 10:21
  • This answered my question. Thanks. – alwayscurious Aug 31 '17 at 10:26
  • Note that you have `Thread.enumerate` to fill an array with the active threads. That could give you an hint on what threads are running. – AxelH Aug 31 '17 at 10:28
  • By dumping the active threads like suggested by @JonJavaK or via `Thread#enumerate` you sould see some other active threads started by the Jvm, as said by @Mark Rotteveel – gervais.b Aug 31 '17 at 10:29

0 Answers0