java多线程分发问题——多线程求和

最近读了的分发部分,又碰到一个网友想利用多线程求和并且汇总求最后结果,具体要求是这样的“写十个线程,第一个线程求1到10的和,第二个11到20的和,第三个求21到30的和...第10个求91到100的和,求十个线程的和”。可以利用CyclicBarrier将分发后的任务汇总,将所有的线程去执行,执行结果后调用显示最后的结果线程。下面写了一段代码可以参考一下。
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
/**

  • 单独的计算线程,比如计算{1...10}的相加
  • @author zhaohb
    */
    public class CounterThread extends Thread{
    private int start;
    private int end;
    private CyclicBarrier barrier ;
    public CounterThread(int id,int start, int end,CyclicBarrier barrier) {
    this.start = start;
    this.end = end;
    this.barrier = barrier;
    setName("Thread-"+id+" ");
    }

    @Override
    public void run() {
    int count = 0;
    for(int i=start;i count += i;
    }
    Counter.totalCount(count);
    try {
    barrier.await();
    } catch (InterruptedException e) {
    e.printStackTrace();
    } catch (BrokenBarrierException e) {
    e.printStackTrace();
    }
    }
    }

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**

  • 测试类入口
  • @author zhaohb
    */
    public class CounterTest {

    public static void main(String[] args) {
    //CyclicBarrier指定了当10个线程运行结束时候,可以进行最后结果展示了
    CyclicBarrier barrier = new CyclicBarrier(10,new TotalTask(new Counter()));
    ExecutorService executorService = Executors.newCachedThreadPool();
    for(int i=0;i<10;i++){
    int start = i*10+1;
    int end = start + 9;
    CounterThread counterThread = new CounterThread(i,start, end,barrier);
    executorService.execute(counterThread);
    }
    executorService.shutdown();
    }
    }

/**

  • 线程结果计算:将单独的线程的计算的结果相加,汇总的到总的结果
  • @author zhaohb
    *
    */
    class Counter {

    private static int count =0;
    public synchronized static int totalCount(int perCount){
    count += perCount;
    return count;
    }

    public int totalResult(){
    return count;
    }

}
/**

  • 最后结算展示线程
  • @author zhb
    *
    */
    class TotalTask implements Runnable{
    private Counter counter ;
    public TotalTask(Counter counter){
    this.counter = counter;
    }

    @Override
    public void run() {
    System.out.println("所有线程运行完毕,总结果为:");

    int total = counter.totalResult();
    System.out.println(total);
    }
    }

你可能感兴趣的:(Java,java,多线程,分发,多线程求和)