您的位置:首页 > 其它

ABC线程如何保证顺序执行 关于多线程的一个小例子

2018-03-07 18:02 344 查看
(谨以此贴感谢boss直聘首席架构师李川的指导)
这个例子是某架构师让我回来一定要理解体会试着做的一个例子,主要是避免对线程的纸上谈兵:
先来段源码
/**
* Creates an Executor that uses a single worker thread operating
* off an unbounded queue. (Note however that if this single
* thread terminates due to a failure during execution prior to
* shutdown, a new one will take its place if needed to execute
* subsequent tasks.)  Tasks are guaranteed to execute
* sequentially, and no more than one task will be active at any
* given time. Unlike the otherwise equivalent
* {@code newFixedThreadPool(1)} the returned executor is
* guaranteed not to be reconfigurable to use additional threads.
*
* @return the newly created single-threaded Executor
*/
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}

    public class AbcThread {
public static void main(String[] args) {
final Thread t1 =new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"run 1");
}
},"T1");
final Thread t2=new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"run 1");
try{
t1.join(10);
}catch (InterruptedException e){
e.printStackTrace();

}
}
},"T2");
final Thread t3=new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"run 3");
try{
t2.join(10);
}catch (InterruptedException e){
e.printStackTrace();

}
}
},"T3");

ExecutorService executorService= Executors.newSingleThreadExecutor();
executorService.submit(t1);
executorService.submit(t2);
executorService.submit(t3);
executorService.shutdown();

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐