java 线程 累加_Java 多线程计算累加数

该博客介绍了一个使用Java实现的多线程累加计算的案例,通过生产者-消费者模型,创建6个线程分别计算1到10000000的累加,最终由主线程打印总和。Calculator类负责每个线程的计算任务,Storage类作为共享仓库进行累加操作。
摘要由CSDN通过智能技术生成

【题意】:开6条线程计算累加1 -> 10000000

【思路】:生产者-消费者 经典模型

多个生产者负责生产(累加)作业

生产者将生产结果存入共享仓库中

消费者(主线程)从共享仓库中取出结果

/**

* 多线程计算累加数

*/

public class Accumulate {

public static void main(String[] args) {

Storage storage = new Storage();

// 为多个计算器对象创建线程

Thread calThread1 = new Thread(new Calculate(1, storage), "Thread-1");

Thread calThread2 = new Thread(new Calculate(2, storage), "Thread-2");

Thread calThread3 = new Thread(new Calculate(3, storage), "Thread-3");

Thread calThread4 = new Thread(new Calculate(4, storage), "Thread-4");

Thread calThread5 = new Thread(new Calculate(5, storage), "Thread-5");

Thread calThread6 = new Thread(new Calculate(6, storage), "Thread-6");

calThread1.start();

calThread2.start();

calThread3.start();

calThread4.start();

calThread5.start();

calThread6.start();

// 打印最终结果

storage.printTotal();

}

}

/**

* 计算器对象,负责计算start -> end

*/

class Calculate implements Runnable {

private Storage storage;

private long start;

public Calculate(long start, Storage storage) {

this.start = start;

this.storage = storage;

}

@Override

public void run() {

long num = start;

long sum = 0;

while (num <= 10000000) {

System.out.println(Thread.currentThread().getName() + " add num " + num);

sum += num;

num += 6;

}

// 线程计算完毕, 调用累加器进行累加

storage.push(sum);

}

}

/**

* 仓库对象,负责累加

*/

class Storage {

private long total = 0;

private int count = 0;

public synchronized void push(long sum) {

total += sum;

count++;

notifyAll();

}

public synchronized void printTotal() {

while (count < 6) {

try {

System.out.println(Thread.currentThread().getName() + " is wait");

wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

System.out.println("storage result = " + total);

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值