首页 > 编程语言 > 详细

java 多线程 join的使用

时间:2020-04-20 23:30:36      阅读:70      评论:0      收藏:0      [点我收藏+]

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;
        }

    }


}

java 多线程 join的使用

原文:https://www.cnblogs.com/wanthune/p/12741409.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!