一. yeild()和join()方法
1.yeild():线程礼让,让当前正在执行的线程可能暂停,但不阻塞
2.yeild():当前正在执行的线程可能暂停,也可能不暂停。
3.yeild():是静态方法,而join()是非静态方法
4.join():能起到线程插队的作用。
案例一:使用yeild(),线程有时礼让,有时不礼让 。
public class TestDemo07 implements Runnable {
public static void main(String[] args) {
// TODO Auto-generated method stub
TestDemo07 t1=new TestDemo07();
TestDemo07 t2=new TestDemo07();
new Thread(t1,"线程A").start();
new Thread(t1,"线程B").start();
new Thread(t1,"线程C").start();
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println(Thread.currentThread().getName()+" 线程正在开始执行");
Thread.yield();
System.out.println(Thread.currentThread().getName()+" 线程停止执行");
}
}
运行结果:
案例二:join()能起到线程插队的作用
package com.zc;
public class TestDemo08 implements Runnable {
public static void main(String[] args) {
//启动我们的线程
TestDemo08 t1=new TestDemo08();
Thread thread = new Thread(t1,"线程A");
thread.start();
//主线程
for(int i = 0; i < 100; i++) {
System.out.println("main"+i);
if(i==30) {
try{
//新增的子线程插队
thread.join();
} catch(InterruptedExcep