码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-08-12 01:28:05      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:service   dex   java   executor   方式   ...   submit   bsp   string   

 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("c"));
23         Thread e = new Thread(new ThreadTest("d"));
24         Thread f = new Thread(new ThreadTest("e"));
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 }

 

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

标签:service   dex   java   executor   方式   ...   submit   bsp   string   

原文地址:https://www.cnblogs.com/warmsmile/p/9461783.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!