没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论




















Java多线程按指定顺序同步执行多线程按指定顺序同步执行
主要介绍了java多线程如何按指定顺序同步执行,文中通过示例代码介绍的非常详细,对大家的学习或者工作具
有一定的参考学习价值,需要的朋友可以参考下
笔者今天看到一个有趣的面试题,如何让多个线程按照既定的顺序依次执行?比如每个线程输出一个整数,
那么期望就是这样的:0,1,2,3,4,5,6,7,8,9. 而不是0,2,4,1,3,5,8,7,9,6
乍一看,这不是反人性的考题吗?多线程本来就以乱序执行出名的。稍加思索,想到3种解决方案,分别用代码实现之。
方法方法1 使用使用newSingleThreadExecutor
newSingleThreadExecutor返回仅仅包含一个线程的线程池,将多个任务交给此Executor时,这个线程池处理完一个任务后接着
处理下一个任务,这样就保证了执行顺序,先提交先执行。如果当前线程意外终止,会创建一个新线程继续执行任务。
示例代码如下:
ExecutorService pool = Executors.newSingleThreadExecutor();
for(int i=0;i<1000;++i) {
final int number = i;
pool.execute(()-> {
System.out.println("I am " + number);
} );
}
pool.shutdown();
方法方法2 使用使用join方法方法
When we call this method using a thread object, it suspends the execution of the calling thread until the object called
finishes its execution.
英语原版其实很拗口,不好理解。简单点说,就是某个线程A调用join,其他线程就要乖乖等A执行完毕才能执行。
示例代码如下:
public class Worker implements Runnable {
private int number;
public Worker(int i) {
number = i;
}
@Override
public synchronized void run() {
System.out.println("I am " + number);
}
}
public class TestWorker {
public static void main(String[] args) {
for(int j=0;j<1000;++j) {
Thread thread = new Thread(new Worker(j));
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
方法方法3 使用使用ThreadPoolExecutor,设置它的核心线程数为,设置它的核心线程数为1
我们先分析一下ThreadPoolExecutor,其构造函数如下
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
资源评论


weixin_38748580
- 粉丝: 5
- 资源: 942
上传资源 快速赚钱
我的内容管理 展开
我的资源 快来上传第一个资源
我的收益
登录查看自己的收益我的积分 登录查看自己的积分
我的C币 登录后查看C币余额
我的收藏
我的下载
下载帮助


安全验证
文档复制为VIP权益,开通VIP直接复制
