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
- Java多线程 --- join
- java 多线程之join
- java多线程-join方法
- JAVA多线程之(join)
- java 多线程join
- java多线程join
- java多线程--join函数
- java多线程join()详解
- Java 多线程之join
- Java多线程join()
- java多线程之join
- Java 多线程:join
- java多线程之join
- java多线程之Join
- Java 多线程join方法
- Java多线程join()
- java多线程join方法
- java多线程join()和join(long millis)
- MySQL key_len 大小的计算
- 《Java 编程思想》-第3章 操作符 笔记
- 获得泛型(generic class)参数类型T的实际类型(actual type)
- The absolut uri: http://java.sun.com/jsp/jstl/core cannot be resolved
- urlretrieve
- Java 多线程:join
- 学习笔记--mysql索引(五) 聚簇索引和覆盖索引
- ArchLinux安装与配置
- 转给六年后的我们
- 控制easyui datagrid 显示和隐藏的正确方法
- 关于pyQT5 + VTK7 的一个实现案例
- Android 数据库升级保留原数据不丢
- HTML5学习随记2⃣️
- js单例模式