问题:三个线程的执行顺序是什么?
public class Test {
public static Thread t1=new Thread(new Runnable() {
@Override
public void run() {
System.out.println("t111111进行执行");
}
});
public static Thread t2=new Thread(new Runnable() {
@Override
public void run() {
System.out.println("t222222进行执行");
}
});
public static Thread t3=new Thread(new Runnable() {
@Override
public void run() {
System.out.println("t333333进行执行");
}
});
public static void main(String[] args) {
t1.start();
t2.start();
t3.start();
}
}
在main方法中开启三个线程,他们的执行顺序是随机的,不是顺序的。
问题二:如何让三个线程顺序执行
答案1:
public static void main(String[] args) {
t1.start();
t1.join();
t2.start();
t2.join();
t3.start();
}
join()方法是让当前主线程等待子线程执行完毕之后再往下执行
答案2:
public static void main(String[] args) throws InterruptedException {
// t1.start();
// t1.join();
// t2.start();
// t2.join();
// t3.start();
ExecutorService executorService= Executors.newSingleThreadExecutor();
executorService.submit(t1);
executorService.submit(t2);
executorService.submit(t3);
}
Executors.newSingleThreadExecutor()实例化的对象一次只有一个线程执行,并且遵循先进先出的原则