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.star
t();
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);
}
}
答案是未必
如图所示,并发累加操作如过没用超过百万,执行速度要比串行的慢。主要是因为上下文切换的开销.
减少上下文切换的方式主要有
-
无锁并发编程:多线程竞争锁时,会引起上下文切换,所以多线程在处理数据时,可以用一些方法来避免使用锁,例如:讲数据的id按照hash算法取模分段,不同的线程处理不同段的数据
-
CAS算法:Java的Atomic包使用CAS算法来更新数据,而不需要加锁
-
使用最小线程:避免创建没必要的线程,减少处于等待状态的线程
-
使用协程:在单线程中实现多任务调度,并在单线程中维持多个线程的切换
原文链接:https://gper.club/articles/7e7e7f7ff7g5agc3g68