JAVA使线程按顺序执行
要使线程能够按顺序执行,主要用到的是Thread类的join()方法。
一个线程可以在其他线程之上调用join()方法,其效果是等待一段时间直到第二个线程结束才继续执 行。如果某个线程在另一个线程t上调用t.join(),此线程将被挂起,直到目标线程t结束才回复。
也可以在调用join()时带上一个超时参数(单位可以是毫秒,或者毫秒和纳秒),这样如果目标线程在这段时间到期时还没有结束的话,join()方法总能返回。
对join()方法的调用可以被中断,做法是在调用线程上调用interrupt()方法。
By Bruce Eckel -JAVA编程思想第21章.
接下来分别使用线程的三种实现方式来进行对join()方法的使用。
java.lang.Thread
package threads;
/**
* @Author: toryxu
* @Date: 2019/3/18 0018 13:31
* @Version 1.0
*/
public class ThreadOne implements Runnable {
public void run(){
System.out.println("JOB ONE");
}
}
package threads;
/**
* @Author: toryxu
* @Date: 2019/3/18 0018 13:32
* @Version 1.0
*/
public class ThreadTwo extends Thread{
public void run(){
System.out.println("JOB TWO");
}
}
package threads;
/**
* @Author: toryxu
* @Date: 2019/3/18 0018 13:33
* @Version 1.0
*/
public class ThreadThree extends Thread {
public void run(){
System.out.println("JOB THREE");
}
}
package threads;
/**
* @Author: toryxu
* @Date: 2019/3/18 0018 13:45
* @Version 1.0
*/
public class ThreadMain {
public static void main(String[] args) {
Thread t1 = new Thread(new ThreadOne());
Thread t2 = new Thread(new ThreadTwo());
Thread t3 = new Thread(new ThreadThree());
try{
t1.start();
t1.join();
t2.start();
t2.join();
t3.start();
t3.join();
System.out.println("let's get it 1");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
这里创建了3个线程类,都继承于Thread类,在main方法中实例化以上类,并依次执行start()方法和join()方法。缺点是每个线程类都需要单独创建。
java.lang.Runnable
package threads;
/**
* @Author: toryxu
* @Date: 2019/3/18 0018 14:00
* @Version 1.0
*/
public class ThreadMain2 {
public static void main(String[] args) throws InterruptedException {
int i ;
for( i=0;i<100;i++){
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
},"join-"+i);
thread.start();
thread.join();
}
System.out.println("let's get it");
}
}
通过Runnable创建thread实例,并对实例执行start和join方法。通过Runnable接口可以直接在new的过程中重写run方法,更加灵活。
java.util.concurrent.Callable
Callable和以上两个方法不一样的是,它可以提供返回值,并可以监听线程进行的情况。
但是它需要通过FutureTask类来接收返回值。以下是实例:
package threads;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* @Author: toryxu
* @Date: 2019/3/18 0018 15:25
* @Version 1.0
* callable
* * 一、创建执行线程的方式三:实现 Callable 接口。 相较于实现 Runnable 接口的方式,方法可以有返回值,并且可以抛出异常。
* *
* * 二、执行 Callable 方式,需要 FutureTask 实现类的支持,用于接收运算结果。 FutureTask 是 Future 接口的实现类
*/
public class ThreadMain3 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
for(int i=0;i<100;i++){
FutureTask<String> ft = new FutureTask<>(new Callable<String>() {
@Override
public String call() throws Exception {
return Thread.currentThread().getName();
}
});
Thread thread = new Thread(ft);
thread.start();
thread.join();
System.out.println(ft.get());
}
}
}
以上三种方法返回值都一样。