如何控制多執行緒執行順序?
阿新 • • 發佈:2018-12-09
介紹
方法1
通過join方法去保證多執行緒順序執行
join:讓主執行緒等待子結束以後才能繼續執行
方法2
ExecutorService executorService = Executors.newSingleThreadExecutor();
FIFO佇列
程式碼
public class Test {
static Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
System. out.println("thread1");
}
});
static Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread2");
}
});
static Thread thread3 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread3");
}
});
static ExecutorService executorService = Executors.newSingleThreadExecutor();
public static void main(String[] args) throws InterruptedException {
// thread1
// thread2
// thread3
method1();
// thread1
// thread2
// thread3
method2();
}
private static void method2() throws InterruptedException {
thread1.start();
thread1.join();
thread2.start();
thread2.join();
thread3.start();
}
private static void method1() {
executorService.submit(thread1);
executorService.submit(thread2);
executorService.submit(thread3);
}
}