Java 多线程:join

来源:互联网 发布:淘宝的二手手机可靠吗 编辑:程序博客网 时间:2024/05/17 22:04

本文内容大多基于官方文档和网上前辈经验总结,经过个人实践加以整理积累,仅供参考。


join() 方法是 java.lang.Thread 类的实例方法,方法签名

public final void join() throws InterruptedException
public final void join(long millis) throws InterruptedException
public final void join(long millis, int nanos) throws InterruptedException

join() 方法使得一个线程在另一个线程结束后再执行,如果在一个线程实例上调用,当前运行的线程将阻塞直至调用 join() 方法的线程实例结束

join() 方法接收 long 类型参数,使得在等待特定毫秒后线程失效

Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever. 

join() 方法还可以额外接收一个 int 类型参数

Waits at most millis milliseconds plus nanos nanoseconds for this thread to die. 

示例:

public static void main(String[] args) throws InterruptedException {    Thread t1 = new Thread(new Runnable() {        @Override        public void run() {            System.out.println("First thread started!");            System.out.println("Ready to sleep 5 seconds!");            try {                Thread.sleep(5000);            } catch (InterruptedException e) {                e.printStackTrace();            }            System.out.println("First thread ended!");        }    });    Thread t2 = new Thread(new Runnable() {        @Override        public void run() {            System.out.println("Second thread started!");            System.out.println("Second thread ended!");        }    });    t1.start();    t1.join();    t2.start();}

如果注释掉 t1.join();,运行结果:

这里写图片描述

去掉注释后运行结果:

这里写图片描述

join() 方法传入一个 long 类型参数,使得最长等待 3 秒

public static void main(String[] args) throws InterruptedException {    Thread t1 = new Thread(new Runnable() {        @Override        public void run() {            System.out.println("First thread started!");            System.out.println("Ready to sleep 5 seconds!");            try {                Thread.sleep(5000);            } catch (InterruptedException e) {                e.printStackTrace();            }            System.out.println("First thread ended!");        }    });    Thread t2 = new Thread(new Runnable() {        @Override        public void run() {            System.out.println("Second thread started!");            System.out.println("Second thread ended!");        }    });    t1.start();    t1.join(3000);    t2.start();}

运行结果:
这里写图片描述

0 0
原创粉丝点击