测试并发编程demo

package cn.com;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.atomic.LongAdder;

import org.junit.Before;
import org.junit.Test;

public class FileTest {

ExecutorService newFixedThreadPool;
ForkJoinPool fjp;

@Before
public void initalMethod() {
    int nThreads = Runtime.getRuntime().availableProcessors();
    this.newFixedThreadPool = Executors.newFixedThreadPool(nThreads);
    fjp = new ForkJoinPool();
}


/**
 * 测试提交多个带有返回值的任务
 * @throws FileNotFoundException
 * @throws InterruptedException
 * @throws ExecutionException
 */
@Test
public void testFile1() throws FileNotFoundException, InterruptedException, ExecutionException {

    // 添加任务
    List<Mytasks> tasks = new ArrayList<Mytasks>();
    tasks.add(new Mytasks());
    tasks.add(new Mytasks());
    tasks.add(new Mytasks());
    tasks.add(new Mytasks());
    tasks.add(new Mytasks());

    List<Future<Long>> res = newFixedThreadPool.invokeAll(tasks);

    LongAdder la = new LongAdder();
    for (int i = 0, size = res.size(); i < size; i++) {
        la.add(res.get(i).get());
    }
    System.out.println(la.sum());

}

}

class Mytasks implements Callable {

LongAdder la = new LongAdder();

@Override
public Long call() throws Exception {
    for (int i = 0; i < 999999; i++) {
        la.increment();
    }
    return la.sum();
}

}

class MyTasksB extends RecursiveTask {

private static final long serialVersionUID = 1L;

ConcurrentLinkedQueue<Integer> clq;

public MyTasksB(ConcurrentLinkedQueue<Integer> clq) {
    super();
    this.clq = clq;
}

@Override
protected Integer compute() {

    if (clq.size() > 10000) {
        MyTasksB forkJob = new MyTasksB(clq);
        forkJob.fork();
    }

    return null;
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值