Thread的join方法demo

2024-10-09 10:03:59 浏览数 (4)

Thread的join方法demo

代码语言:javascript复制
/**
 * 关于join官方的解释是 Waits for this thread to die. 也就是等待一个线程结束。
 */
public class ThreadJoinTest {
    public static void main(String[] args) throws InterruptedException {
        long startTimestamp = System.currentTimeMillis();

        // 假设有三台机器,开启三个线程。
        Thread m1 = new Thread(new CaptureRunnable("M1", 1_000L));
        Thread m2 = new Thread(new CaptureRunnable("M2", 2_000L));
        Thread m3 = new Thread(new CaptureRunnable("M3", 3_000L));

        /**
         * 可以看到三个线程还没走完,就提前把时间打印出来了,这个不是我我们想要的效果,那么我们让三个线程join一下试试:
         * Save data begin timestamp is 1665222904024, end timestamp is 1665222904025
         * Spend time is 1
         * M1 completed data capture at timestamp [1665222905026] and successful.
         * M2 completed data capture at timestamp [1665222906025] and successful.
         * M3 completed data capture at timestamp [1665222907026] and successful.
         */
        m1.start();
        m2.start();
        m3.start();

        /**
         *
         * 打开注释输出:
         * M1 completed data capture at timestamp [1665222874569] and successful.
         * M2 completed data capture at timestamp [1665222875569] and successful.
         * M3 completed data capture at timestamp [1665222876569] and successful.
         * Save data begin timestamp is 1665222873568, end timestamp is 1665222876569
         * Spend time is 3001
         */
//        m1.join();
//        m2.join();
//        m3.join();

        long endTimestamp = System.currentTimeMillis();

        System.out.printf("Save data begin timestamp is %s, end timestamp is %sn", startTimestamp, endTimestamp);
        System.out.printf("Spend time is %sn", endTimestamp - startTimestamp);
    }


    /**
     * 采集服务器节点的任务。
     */
    static class CaptureRunnable implements Runnable {
        // 机器节点的名称
        private String machineName;
        // 采集花费时间
        private long spendTime;

        public CaptureRunnable(String machineName, long spendTime) {
            this.machineName = machineName;
            this.spendTime = spendTime;
        }

        @Override
        public void run() {
            // do the really capture data.
            try {
                Thread.sleep(spendTime);
                System.out.printf(machineName   " completed data capture at timestamp [%s] and successful.n", System.currentTimeMillis());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        public String getResult() {
            return machineName   " finish.";
        }
    }

}

0 人点赞