zoukankan      html  css  js  c++  java
  • Java线程之join

    简述

    Thread类的join方法用来使main线程进入阻塞状态,进而等待调用join方法的线程执行,join有三个重载方法:

    public final void join()
    使主线程进入阻塞状态,直到调用join的线程执行完成,如果线程被中断将抛出InterruptedException异常
    
    public final synchronized void join(long millis):
    使主线程最多阻塞指定时间(毫秒)
    
    public final synchronized void join(long millis, int nanos)
    使主线程最多阻塞指定时间(毫秒),可以精确到纳秒

    实例

    主线程等待所有子线程先执行完成

    package com.lkf.mulithread;
    
    public class ThreadJoinExample {
        public static void main(String[] args) {
            Thread t1 = new Thread(new MyRunnable(), "线程t1");
            Thread t2 = new Thread(new MyRunnable(), "线程t2");
            Thread t3 = new Thread(new MyRunnable(), "线程t3");
    
            t1.start();
    
            //两秒钟以后启动第二个线程
            try {
                t1.join(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
            t2.start();
    
            //第一个线程完成之后启动第三个线程
            try {
                t1.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
            t3.start();
    
            //三个子线程先执行完,然后继续主线程
            try {
                t1.join();
                t2.join();
                t3.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
            System.out.println("所有线程执行完毕");
        }
    
    }
    
    class MyRunnable implements Runnable {
    
        @Override
        public void run() {
            System.out.println("Thread started:::" + Thread.currentThread().getName());
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Thread ended:::" + Thread.currentThread().getName());
        }
    }
    

    结果:

    Thread started:::线程t1
    Thread started:::线程t2
    Thread ended:::线程t1
    Thread started:::线程t3
    Thread ended:::线程t2
    Thread ended:::线程t3
    所有线程执行完毕
    博主文章同步发布:https://blog.csdn.net/u010647035/article/details/83959552
  • 相关阅读:
    JAVA数据库连接池
    数据库连接池总结 Proxool
    Linux下挂载ISO文件
    Runtime.getRuntime().addShutdownHook()的使用
    tomcat original passports setting
    JDBC之通过DatabaseMetaData对象了解数据库的信息
    linux下mysql远程登陆
    教您如何安全的应用 MySQL
    Eclipse中cvs的使用介绍
    WM_COPYDATA
  • 原文地址:https://www.cnblogs.com/liukaifeng/p/10052665.html
Copyright © 2011-2022 走看看