加入线程
-
join():当前线程暂停,等待指定的线程执行结束后,当前线程再继续。
-
join(int):可以等待指定的毫秒之后继续。
final Thread t1 = new Thread() { public void run() { for(int i = 0; i < 50; i++) { System.out.println(getName() + "...aaaaaaaaaaaaaaaaaaaaaa"); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } } }; Thread t2 = new Thread() { public void run() { for(int i = 0; i < 50; i++) { if(i == 2) { try { //t1.join(); //插队,加入 t1.join(30); //加入,有固定的时间,过了固定时间,继续交替执行 Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(getName() + "...bb"); } } }; t1.start(); t2.start();
package com.heima.threadmethod;
public class Demo05_Join {
public static void main(String[] args) {
// 匿名内部类在使用它所在方法中的局部变量的时候,必须用final修饰.
final Thread t1 = new Thread() {
public void run() {
for(int i = 0; i < 10; i++) {
System.out.println(getName() + "...aaaaaaaaaaaaa");
}
}
};
Thread t2 = new Thread() {
public void run() {
for(int i = 0; i < 10; i++) {
if(i == 2) {
try {
//t1.join();
t1.join(1); //插队指定的时间,过了指定时间后,两条线程交替执行
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(getName() + "...bb");
}
}
};
t1.start();
t2.start();
}
}
本文深入探讨Java中线程的join方法,解释了如何使用join()和join(int)使线程等待,以及它们在多线程编程中的作用。通过示例代码展示了不同情况下线程的执行顺序,帮助读者理解线程同步的概念。
232

被折叠的 条评论
为什么被折叠?



