
正文
【Java并发】线程的顺序执行
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
/**
* 问题:有线程a、b、c,如何让它们顺序执行?
* 方式一:可用Join()方法实现
* 方式二:可用newSingleThreadExecutor()
* Created by Smile on 2018/8/12.
*/
public class ThreadByOrder { public static void main(String[] args) throws InterruptedException { Thread a = new Thread(new ThreadTest("a"));
Thread b = new Thread(new ThreadTest("b"));
Thread c = new Thread(new ThreadTest("c")); //方式一实现
a.start();
a.join();
b.start();
b.join();
c.start(); Thread d = new Thread(new ThreadTest("d"));
Thread e = new Thread(new ThreadTest("e"));
Thread f = new Thread(new ThreadTest("f"));
//方式二实现
ExecutorService singlePool = Executors.newSingleThreadExecutor();
singlePool.submit(d);
singlePool.submit(e);
singlePool.submit(f);
singlePool.shutdown();
} static class ThreadTest implements Runnable{ private String threadName; public ThreadTest(String name){
this.threadName = name;
} public ThreadTest() {
} public void run() {
if("a".equals(threadName)||"f".equals(threadName))
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread "+threadName+" is running...");
}
}
}







