用java多线程实现1+2+3+..+100和1!+2!+...+10!

解决方案 »

  1.   


    //从1+2+..99
    public class Test {
    public static class MyCallable implements Callable<Integer>{
    private Integer start;
    private Integer end;
    public MyCallable(Integer start,Integer end){
    this.start = start;
    this.end = end;
    }
    public Integer call(){
    System.out.println(Thread.currentThread().getName());
    int sum = 0;
    for(int i=start;i<end;i++){
    sum +=i;
    }
    return sum;
    }
    }
    public static void main(String args[])throws Exception{
    int threadCount = 2;
    int sum = 0;
    ExecutorService service = Executors.newFixedThreadPool(threadCount);
    for(int i=0;i<threadCount;i++){
    sum += service.submit(new MyCallable(i*50,(i+1)*50)).get();
    }
    System.out.println(sum);
    service.shutdown();
    }
    }
      

  2.   


    public class Test {
    static int sum1 = 0; static int i1 = 1; static int sum2 = 0; static int i2 = 1; /**计算1+2+...+100*/
    static Runnable add = new Runnable() {
    public synchronized void run() {
    sum1 += i1++;
    } }; /**计算阶乘*/
    static Runnable factorial = new Runnable() {
    public synchronized void run() {
    int result = 1;
    for (int i = 1; i <= i2; i++) {
    result *= i;
    }
    sum2 += result;
    i2++;
    } }; static synchronized int calc1(int n) {
    Thread[] threads = new Thread[n];
    for (int i = 0; i < n; i++) {
    threads[i] = new Thread(add);
    threads[i].start();
    }
    while (i1 != n + 1) {
    ;
    }
    return sum1;
    } static synchronized int calc2(int n) {
    Thread[] threads = new Thread[n];
    for (int i = 0; i < n; i++) {
    threads[i] = new Thread(factorial);
    threads[i].start();
    }
    while (i2 != n + 1) {
    ;
    }
    return sum2;
    }

    public static void main(String[] args) {
    System.out.println(calc1(100));
    System.out.println(calc2(10));
    }}
      

  3.   

    不久前看到一个使用jdk7 fork-join 框架计算 fib数列的,