在面试时我们常被问及如何让java线程顺序执行,这我们就要了解一下 join() 方法了,我们首先来看下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);
}
我们看到注释 :
Waits for this thread to die.(即等待调用此方法的线程执行完毕再继续执行)
其实他调用了join(long millis)方法,内部调用了wait方法实现等待,至此,我们就可以让需要优先执行的线程执行join,等其执行完毕之后,后面的线程才会执行,代码如下:
两个线程先后执行:
package com.c.study.thread;
/**
* @Author geyuecang
* @Date 2019/10/11 20:23
* @Des
**/
public class JoinThread {
public static void main(String[] args) {
Thread joinThread = new Thread(new Runnable2());
Thread thread1 = new Thread(new Runnable1(joinThread));
thread1.start();
joinThread.start();
}
static class Runnable1 implements Runnable {
private final Thread thread;
public Runnable1(Thread thread) {
this.thread = thread;
}
@Override
public void run() {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Runnable111111");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Runnable1 睡醒了");
}
}
static class Runnable2 implements Runnable {
@Override
public void run() {
System.out.println("Runnable22222");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Runnable2 睡醒了");
}
}
}
多个线程顺序执行:
public class UseJoin {
static class JumpQueue implements Runnable {
private Thread thread;//用来插队的线程
public JumpQueue(Thread thread) {
this.thread = thread;
}
public void run() {
try {
System.out.println(thread.getName()+" will be join before "
+Thread.currentThread().getName());
Thread.sleep(3000);
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" terminted.");
}
}
public static void main(String[] args) throws Exception {
Thread previous = Thread.currentThread();//现在是主线程
for (int i = 0; i < 10; i++) {
//i=0,previous 是主线程,i=1;previous是i=0这个线程
Thread thread = new Thread(new JumpQueue(previous), String.valueOf(i));
thread.start();
previous = thread;
}
System.out.println(Thread.currentThread().getName() + " terminate.");
}
}