yield
礼让线程,让当前正在执行的线程暂停,但不阻塞。
线程从运行状态转为就绪状态。
让CPU重新调度,礼让不一定成功!
public class TestYield {
public static void main (String[] args) {
MyYield myYield = new MyYield();
new Thread(myYield,"A").start();
new Thread(myYield,"B").start();
}
}
class MyYield extends Thread{
@Override
public void run () {
System.out.println(Thread.currentThread().getName()+"线程开始");
Thread.yield();
System.out.println(Thread.currentThread().getName()+"线程结束");
}
}
执行结果:
礼让成功
A线程开始
B线程开始
A线程结束
B线程结束
礼让成功
A线程开始
A线程结束
B线程开始
B线程结束
join
合并线程,待当前想成执行完后,在执行其他线程,其他线程阻塞。(可以想像成插队!)
public class TestJoin implements Runnable{
@Override
public void run () {
for (int i = 1; i <=1000 ; i++) {
System.out.println("vip线程来了"+i);
}
}
public static void main (String[] args) throws InterruptedException {
TestJoin testJoin = new TestJoin();
Thread thread = new Thread(testJoin);
thread.start();
//主线程
for (int i = 1; i <=1000 ; i++) {
if(i==200){
thread.join();
}
System.out.println("main线程来了"+i);
}
}
}