微信搜索《Java鱼仔》,每天一个知识点不错过
(一)每天一个知识点
如何让多个线程按顺序执行?
(二)结论
1.主线程中使用join 2.子线程中使用join 3.使用单一化线程池
(三)再多学一点
我们都知道线程的执行顺序是无序的,但是有的时候我们希望线程按顺序执行该怎么做呢?我在下面提供了三种方式: 1.主线程中使用join
publicstaticvoidmain(String[] args) throwsInterruptedException { Threada1=newThread(newRunnable() { publicvoidrun() { System.out.println(Thread.currentThread().getName()+"打开冰箱"); } }); Threada2=newThread(newRunnable() { publicvoidrun() { System.out.println(Thread.currentThread().getName()+"取出物品"); } }); Threada3=newThread(newRunnable() { publicvoidrun() { System.out.println(Thread.currentThread().getName()+"关闭冰箱"); } }); a1.start(); a1.join(); a2.start(); a2.join(); a3.start(); a3.join(); }
2.子线程中使用join
publicstaticvoidmain(String[] args) throwsInterruptedException { Threada1=newThread(newRunnable() { publicvoidrun() { System.out.println(Thread.currentThread().getName()+"打开冰箱"); } }); Threada2=newThread(newRunnable() { publicvoidrun() { try { a1.join(); } catch (InterruptedExceptione) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"取出物品"); } }); Threada3=newThread(newRunnable() { publicvoidrun() { try { a2.join(); } catch (InterruptedExceptione) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"关闭冰箱"); } }); a1.start(); a2.start(); a3.start(); }
3.使用单一化线程池,单一化线程池一次只提供一个线程,相当于单线程的操作。
staticExecutorServiceservice=Executors.newSingleThreadExecutor(); publicstaticvoidmain(String[] args) { Threada1=newThread(newRunnable() { publicvoidrun() { System.out.println(Thread.currentThread().getName()+"打开冰箱"); } }); Threada2=newThread(newRunnable() { publicvoidrun() { System.out.println(Thread.currentThread().getName()+"取出物品"); } }); Threada3=newThread(newRunnable() { publicvoidrun() { System.out.println(Thread.currentThread().getName()+"关闭冰箱"); } }); service.submit(a1); service.submit(a2); service.submit(a3); }