(一):yield()
(二): join()
对于第一点举个栗子:
public class SysController {
public static void main(String[] args) throws InterruptedException{
Thread thread0 = new Thread(()-> {
System.out.println(Thread.currentThread().getName()+"Thread0 completed");
});
Thread thread1 = new Thread(()->{
System.out.println(Thread.currentThread().getName()+"Thread1 started");
System.out.println(Thread.currentThread().getName()+"Thread1 sleeping for seconds");
try{
Thread.sleep(2000);
}catch (InterruptedException e){
e.printStackTrace();
};
System.out.println(Thread.currentThread().getName()+"Thead1 completed");
});
//线程1
thread0.start();
//线程1调用join()
thread0.join();
thread1.start();
}
}
输出:
解释:
在主线程(main)中执行thread0时调用 thread0.join();时,会让主线程停止,先让thread0执行完后main线程在执行thread1。这就验证了1和2
又一个栗子:
public class SysController {
public static void main(String[] args) throws InterruptedException{
Thread thread1 = new Thread(()-> {
System.out.println(Thread.currentThread().getName()+"Thread1 completed");
});
Thread thread0 = new Thread(()->{
try{
thread1.join();
}catch (InterruptedException e){
e.printStackTrace();
};
System.out.println(Thread.currentThread().getName()+"Thead0 completed");
});
//线程1
thread0.start();
//线程1调用join()
//thread0.join();
thread1.start();
}
输出:
解释:
thread1.join(); 导致main线程先让Thread1执行完,在执行Thread0,同时验证了第2点。
总结: