Java: How to use Thread.join

后端 未结 3 386
清歌不尽
清歌不尽 2020-11-30 07:09

I\'m new to threads. How can I get t.join to work, whereby the thread calling it waits until t is done executing?

This code would just freeze the progr

3条回答
  •  北海茫月
    2020-11-30 07:17

    Use something like this:

    public void executeMultiThread(int numThreads)
       throws Exception
    {
        List threads = new ArrayList();
    
        for (int i = 0; i < numThreads; i++)
        {
            Thread t = new Thread(new Runnable()
            {
                public void run()
                {
                    // do your work
                }
            });
    
            // System.out.println("STARTING: " + t);
            t.start();
            threads.add(t);
        }
    
        for (int i = 0; i < threads.size(); i++)
        {
            // Big number to wait so this can be debugged
            // System.out.println("JOINING: " + threads.get(i));
            ((Thread)threads.get(i)).join(1000000);
        }
    

提交回复
热议问题