java多线程运行代码,Java – 多线程代码在更多内核上运行速度更快

我只是在4核机器上运行一些多线程代码,希望它比单核机器更快.这是一个想法:我有一个固定数量的线程(在我的情况下,每个核心一个线程).每个线程都执行以下形式的Runnable:

private static int[] data; // data shared across all threads

public void run() {

int i = 0;

while (i++ < 5000) {

// do some work

for (int j = 0; j < 10000 / numberOfThreads) {

// each thread performs calculations and reads from and

// writes to a different part of the data array

}

// wait for the other threads

barrier.await();

}

}

在四核计算机上,此代码使用4个线程比使用1个线程执行更差.即使有CyclicBarrier的开销,我也会认为代码的执行速度至少要快2倍.为什么它运行得慢?

编辑:这是我尝试过的忙等待实现.不幸的是,它使程序在更多核心上运行得更慢(也在另一个问题here中讨论):

public void run() {

// do work

synchronized (this) {

if (atomicInt.decrementAndGet() == 0) {

atomicInt.set(numberOfOperations);

for (int i = 0; i < threads.length; i++)

threads[i].interrupt();

}

}

while (!Thread.interrupted()) {}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值