并发挑战(一)
强烈推介IDEA2020.2破解激活,IntelliJ IDEA 注册码,2020.2 IDEA 激活码
并发编程的目的是为了让程序运行的更快一点,但是,并不是启动更多的线程就可以让程序执行的效率更高,运行更快。进行并发编程时,如果希望通过多线程执行让程序变得更快,会面临非常大的挑战,如:上下文切换、死锁以及受限制于阴间和软件的资源限制等问题。
单核处理器也支持多线程去执行代码,CPU是通过给每个程序分配时间片来实现并行机制。时间片是CPU分配给各个线程的时间。时间片非常短,CPU通过不断切换线程执行,让我们感觉上是并发执行。 CPU通过时间片分配算法来循环执行任务,当前时间片执行完成之后,记住当前任务执行的状态,以便于下次切换回来的时候,加载这个状态,继续执行,所以任务从保存到再加载的过程就是一次上下文切换。 但是,上下文切换会影响多线程的执行速度。 下面代码演示的是串行和并发执行并累加操作的时间,但是并发执行一定比串行快吗?
public class ConcurrencyTest {
private static final long count = 10000l;
public static void main(String[] args) throws InterruptedException {
concurrency();
serial();
}
private static void serial() {
long start = System.currentTimeMillis();
int a = 0;
for (long i = 0; i < count; i++) {
a += 5;
}
int b = 0;
for (long i = 0; i < count; i++) {
b--;
}
long time = System.currentTimeMillis() - start;
System.out.println("serial:" + time+"ms,b="+b+",a="+a);
}
private static void concurrency() throws InterruptedException {
long start = System.currentTimeMillis();//获取当前时间戳
Thread thread = new Thread(() -> {
int a = 0;
for (long i = 0;i < count;i++){
a += 5;
}
});
thread.start();
int b = 0;
for (long i = 0;i < count;i++) {
b--;
}
long time = System.currentTimeMillis() - start;
thread.join();//调用线程等待,只有该线程执行完成之后,才能往下执行
System.out.println("concurrency :" + time+"ms,b="+b);
}
}
答案是未必
如图所示,并发累加操作如过没用超过百万,执行速度要比串行的慢。主要是因为上下文切换的开销.
减少上下文切换的方式主要有
原文链接:https://gper.club/articles/7e7e7f7ff7g5agc3g68
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有