Java: How to use Thread.join

后端 未结 3 397
清歌不尽
清歌不尽 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:20

    You have to call the join method on the other Thread.
    Something like:

    @Override
    public void run() {
        String[] info = new String[] {"abc", "def", "ghi", "jkl"};
    
        Thread other = new OtherThread();
        other.start();
    
        for (int i = 0; i < info.length; i++) {
            try {
                if (i == info.length / 2) {
                    other.join();    // wait for other to terminate
                }
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.printf("%s %s%n", getName(), info[i]);
        }       
    }
    

提交回复
热议问题