如何讓多個執行緒按照順序執行
阿新 • • 發佈:2018-12-15
兩種方法:
假設如下:
如果有a,b,c三個執行緒,我們依次執行這三個執行緒。因為不保證有序性,可能執行出來是混亂的
解決如下:
第一種使用join()方法,這個方法的作用是,讓當前執行執行緒等待直到呼叫join方法的執行緒結束執行
程式碼如下:
class Thread1 extends Thread{ public void run(){ try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Threada"); } } class Thread2 extends Thread{ public void run(){ try { Thread.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Threadb"); } } class Thread3 extends Thread{ public void run(){ System.out.println("Threadc"); } } public class Main { public static void main(String[] args) throws InterruptedException { Thread1 thread1=new Thread1(); thread1.start(); thread1.join(); Thread2 thread2=new Thread2(); thread2.start(); thread2.join(); Thread3 thread3=new Thread3(); thread3.start(); // ExecutorService executorService=Executors.newSingleThreadExecutor(); // executorService.execute(thread1); // executorService.execute(thread2); // executorService.execute(thread3); // executorService.shutdown(); } }
第二種是通過執行緒池裡的方法:我們使用單執行緒池,這樣就能根據傳入的順序執行執行緒。
package didi; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; class Thread1 extends Thread{ public void run(){ try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Threada"); } } class Thread2 extends Thread{ public void run(){ try { Thread.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Threadb"); } } class Thread3 extends Thread{ public void run(){ System.out.println("Threadc"); } } public class Main { public static void main(String[] args) throws InterruptedException { Thread1 thread1=new Thread1(); // thread1.start(); // thread1.join(); Thread2 thread2=new Thread2(); // thread2.start(); // thread2.join(); Thread3 thread3=new Thread3(); // thread3.start(); ExecutorService executorService=Executors.newSingleThreadExecutor(); executorService.execute(thread1); executorService.execute(thread2); executorService.execute(thread3); executorService.shutdown(); } }