java多线程如何实现执行顺序
解决方法:
1.使用join方法把指定的线程加入到当前线程
Runnable runnable = new Runnable() {
@Override public void run() {
System.out.println(Thread.currentThread().getName()+"开始执行");
}
};
Thread t1 = new Thread(runnable);
Thread t2 = new Thread(runnable);
Thread t3 = new Thread(runnable);
try {
t1.start();
t1.join();
t2.start();
t2.join();
t3.start();
t3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
2.使用newSingleThreadExecutor()方法可以创建单一线程池,单一线程池可以实现以队列的方式来执行任务。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import myrunnable.MyRunnable;
public class Run {
public static void main(String[] args) {
ExecutorService
executorService =Executors.newSingleThreadExecutor();
for (int i = 0; i < 3; i++) {//添加三个线程,MyRunnable实现了Runnable接口
executorService.execute(new MyRunnable());
}
}
}