join()方法作用
当在主线程当中执行到t1.join()方法时,就认为主线程应该把执行权让给t1
废话不多说看代码:
package com.toov5.thread;
public class JoinThreadTest {
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<10;i++){
try {
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
System.out.println(Thread.currentThread().getName()+"i"+i);
}
}
});
t1.start();
//主线程在此调用t1.join()方法,就认为主线程应该把执行权交给t1 让t1执行完毕后再执行主线程
try {
t1.join();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// t1.start();
for(int i=0; i<10;i++){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("main"+"i"+i);
}
}
}
如果先调用join的方法在执行 启动线程
package com.toov5.thread;
public class JoinThreadTest {
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<10;i++){
try {
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
System.out.println(Thread.currentThread().getName()+"i"+i);
}
}
});
// t1.start();
//主线程在此调用t1.join()方法,就认为主线程应该把执行权交给t1 让t1执行完毕后再执行主线程
try {
t1.join();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
t1.start();
for(int i=0; i<10;i++){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("main"+"i"+i);
}
}
}
结果分别:
和
其实质就是类似于一个加入线程
join(), 当前线程暂停, 等待指定的线程执行结束后, 当前线程再继续
join(int), 可以等待指定的毫秒之后继续
package com.toov5.test;
public class demoJoin {
public static void main(String[] args) {
Thread t1= new Thread() {
@Override
public void run() {
for(int i =0; i<10; i++) {
System.out.println(getName()+"...bbbbb");
}
}
};
Thread t2 = new Thread() {
public void run() {
for (int i = 0; i < 10; i++) {
if (i==2) {
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(getName()+"...aaaaa");
}
};
};
t1.start();
t2.start();
}
}
可以看到:
aaa执行了两次后 就开始执行 bbb一直执行完毕 才可以执行 aaaaaa
也可以执行插队时间 join(1) //过了指定的插队时间后 两个线程交替执行