zoukankan      html  css  js  c++  java
  • 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;
            }
    
        }
    
    
    }
    
    
  • 相关阅读:
    CDQ分治入门
    BSGS算法初探
    简析平衡树(三)——浅谈Splay
    简析平衡树(一)——替罪羊树 Scapegoat Tree
    NOIP2018初赛 解题报告
    【BZOJ1101】[POI2007] Zap(莫比乌斯反演)
    WQS二分学习笔记
    【洛谷2664】树上游戏(点分治)
    同余问题(一)——扩展欧几里得exgcd
    二叉搜索树(BST)学习笔记
  • 原文地址:https://www.cnblogs.com/wanthune/p/12741409.html
Copyright © 2011-2022 走看看