join():
等待该线程终止
等待加入的其他线程结束后再继续执行本线程
代码演示
public class MyThread5 implements Runnable{
public void run(){
for (int i = 0; i <= 30; i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
public static void main(String[] args) {
//创建子线程对象
Runnable runnable = new MyThread5();
Thread t = new Thread(runnable, "mythread");
t.start();
//主线程main做的事情
for (int i = 0; i <= 20; i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
//当i=5的时候,强制把t线程加入执行
//线程调度:join()----等待线程终止:等待t线程执行结束后,main主线程再继续执行
if (i==5){
try {
t.join();
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
}
yield()
暂停当前正在执行的线程对象,并执行其他线程,线程礼让
只是提供一种可能,但不能保证一定会实现礼让
代码演示
public class MyThread6 implements Runnable {
public void run(){
for (int i = 0; i <=4 ; i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
if (i==3){
//线程礼让,线程调度:yield()
Thread.yield();
}
}
}
public static void main(String[] args) {
//创建两个线程对象
Runnable runnable=new MyThread6();
Thread t1=new Thread(runnable,"线程A");
Thread t2=new Thread(runnable,"线程B");
t1.start();
t2.start();
}
}
请注意区分join()
yield():礼让,放手。当线程处于就绪状态
join():阻塞当前线程,直到其他线程执行完毕,当前线程才进入就绪状态