并发挑战(一)

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值