线程的加入方法

时间:2019-05-09 14:10:58

标签: java multithreading

我注意到Join方法的有趣行为,这非常令人困惑,多线程处理可能已经过时和过时了(在Java 8的lambda / stream之后),但仍然好奇地发现我是否丢失了某些东西,从未使用过线程处理实时项目。

class JoinDemoThread1 implements Runnable {
    String threadName;

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("Testing in demothread1=" + i);
        }
    }
}

class JoinDemoThread2 implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("Testing in demothread2=" + i);
        }
    }
}

public class JoinDemo {
    public static void main(String args[]) {
        JoinDemoThread1 joinDemoThread1 = new JoinDemoThread1();
        JoinDemoThread2 joinDemoThread2 = new JoinDemoThread2();

        Thread demoThread1 = new Thread(joinDemoThread1);
        Thread demoThread2 = new Thread(joinDemoThread2);

        demoThread1.start();
        demoThread2.start();

        // wait for threads to end
        try {
            demoThread1.join();
            demoThread2.join();
        } catch (Exception e) {
            System.out.println("Interrupted");
        }

        System.out.println("Ending Main program.");
    }
}

1 个答案:

答案 0 :(得分:0)

运行给定代码时的输出:

$this

肯定看起来根本没有多线程。这是因为线程完成得如此之快,以至于调度程序没有理由交错线程。如果需要更密集的过程,您将看到更多预期的输出。

例如,当稍微延迟线程时:

Testing in demothread1=0
Testing in demothread1=1
Testing in demothread1=2
Testing in demothread1=3
Testing in demothread1=4
Testing in demothread2=0
Testing in demothread2=1
Testing in demothread2=2
Testing in demothread2=3
Testing in demothread2=4
Ending Main program.

输出将是:

class JoinDemoThread2 implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException ignored) {}
            System.out.println("Testing in demothread2=" + i);
        }
    }
}