【Java并发】线程的顺序执行

2018-08-14 09:56:04来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

 1 /**
 2  * 问题:有线程a、b、c,如何让它们顺序执行?
 3  * 方式一:可用Join()方法实现
 4  * 方式二:可用newSingleThreadExecutor()
 5  * Created by Smile on 2018/8/12.
 6  */
 7 public class ThreadByOrder {
 8 
 9     public static void main(String[] args) throws InterruptedException {
10 
11         Thread a = new Thread(new ThreadTest("a"));
12         Thread b = new Thread(new ThreadTest("b"));
13         Thread c = new Thread(new ThreadTest("c"));
14 
15         //方式一实现
16         a.start();
17         a.join();
18         b.start();
19         b.join();
20         c.start();
21 
22         Thread d = new Thread(new ThreadTest("d"));
23         Thread e = new Thread(new ThreadTest("e"));
24         Thread f = new Thread(new ThreadTest("f"));
25         //方式二实现
26         ExecutorService singlePool = Executors.newSingleThreadExecutor();
27         singlePool.submit(d);
28         singlePool.submit(e);
29         singlePool.submit(f);
30         singlePool.shutdown();
31     }
32 
33     static class ThreadTest implements Runnable{
34 
35         private String threadName;
36 
37         public ThreadTest(String name){
38             this.threadName = name;
39         }
40 
41         public ThreadTest() {
42         }
43 
44         public void run() {
45             if("a".equals(threadName)||"f".equals(threadName))
46                 try {
47                     Thread.sleep(5000);
48                 } catch (InterruptedException e) {
49                     e.printStackTrace();
50                 }
51             System.out.println("thread "+threadName+" is running...");
52         }
53     }
54 }

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Spring和Mybatis整合异常:expected at least 1 bean which qual

下一篇:SpringBoot常用注解的介绍及简单使用