join()方法的理解
这是官方文档的注释:
/**
* Waits for this thread to die.
*
* <p> An invocation of this method behaves in exactly the same
* way as the invocation
*
* <blockquote>
* {@linkplain #join(long) join}{@code (0)}
* </blockquote>
*
* @throws InterruptedException
* if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
*/
public final void join() throws InterruptedException {
join(0);
}
join()方法的作用:Waits for this thread to die.即:等待这个线程结束。
我们可以看个demo
package com.example.demo.threadpool;
public class ThreadDemo {
public static void main(String[] args) throws InterruptedException {
Thread.sleep(300);
Thread thread1 = new Thread(() -> {
System.out.println(Thread.currentThread().getName());
}, "thread1");
Thread thread2 = new Thread(() -> {
System.out.println(Thread.currentThread().getName());
}, "thread2");
Thread thread3 = new Thread(() -> {
System.out.println(Thread.currentThread().getName());
}, "thread3");
thread2.start();
thread2.join();
thread1.start();
thread1.join();
thread3.start();
thread3.join();
// Thread.currentThread().yield();
System.out.println("main:" + Thread.currentThread().getName());
}
}
大家可以猜猜结果 如果没有join 结果又会怎么样呢?
根据代码中的定义 只有 thread2 运行完毕后 才会运行thread1 然后接着才是thread3 最后才是主线程 如果没有join() 那么结果就是随机的。
这是代码的运行结果 :
**
**thread2
thread1
thread3
main:main****
关于yield:
简单说下,这个方法大家了解就行,不实用,在多线程里面有各种各样的方法,其中有一个礼让 的方法很有意思,现实生活中所谓的礼让,就是“委屈自己方便他人”!比如过马路,汽车礼让行人,当然这是在国外吐舌头,国内过个斑马线是要看司机的性格的!那么在线程中是个什么情况呢,下面看一下demo(同上代码 把join去掉就行了)
结果可能会出乎意料哦
yield这个方法只会去告诉调度器 你该让出时间片了 让别的线程去跑会 然后任务调度器可不一定会听它的 所有它的结果也是不确定的。