java 多线程 join的使用

JOIN: 暂停当前线程,等待目标线程执行完成,再执行当前线程

package com.spring.thread.demo.test;

public class ThreadJoinDemo {

    public static void main(String[] args) throws InterruptedException {
        System.out.println("--------单线程--------->");
        f1();
        System.out.println("---------5 个线程------------->");
        f2();

    }

    private static void f1() throws InterruptedException {
        long t = System.currentTimeMillis();
        Thread1 thread1 = new Thread1(0, 10000000);
        thread1.start();
        //让main 线程暂停,等待thread1线程结束后再取结果
        thread1.join();
        int c = thread1.count;
        t = System.currentTimeMillis() - t;
        System.out.println("c:" + c);
        System.out.println("time:" + t);


    }

    private static void f2() throws InterruptedException {
        long t = System.currentTimeMillis();
        Thread1[] a = new Thread1[5];
        for (int i = 0; i < a.length; i++) {
            a[i] = new Thread1(i*2000000, (i+1)*2000000);
            a[i].start();        
        }
        
        int sum = 0;
        for (int i = 0; i < a.length; i++) {
            a[i].join();
            sum+= a[i].count;
        }
        
        t = System.currentTimeMillis() - t;
        System.out.println("sum:" + sum);
        System.out.println("time:" + t);
    }

    static class Thread1 extends Thread {
        int start;
        int end;
        int count;

        public Thread1(int start, int end) {
            if (start < 3) {
                start = 3;
                count = 1;
            }
            this.start = start;
            this.end = end;
        }


        public void run() {
            for (int i = start; i < end; i++) {
                if (isPrime(i)) {
                    count++;
                }
            }
        }

        private boolean isPrime(int i) {
            double d = 1 + Math.sqrt(i);
            for (int j = 2; j < d; j++) {
                if (i % j == 0) {
                    return false;
                }
            }
            return true;
        }

    }


}

猜你喜欢

转载自www.cnblogs.com/wanthune/p/12741409.html