【javaマルチスレッド】セグメント乗算

4232 ワード

階乗スレッドクラス:Factorial.javaは値を返す必要があるため、Callableインタフェースを実現し、call()は計算結果を返す
import java.util.concurrent.Callable;

public class Factorial implements Callable{

    private long val1;
    private long val2;
    private long sum;
    private long time;
    public Factorial(long val1, long val2) {
        this.val1 = val1;
        this.val2 = val2;
    }

    public  void  sum() throws InterruptedException {
        long temp =val1;
        for (long i = 1; i < val2 - val1 + 1; i++) {
            temp *= (val1+i);
        }
        sum = temp;
    }

    @Override
    public Object call() throws Exception {

        System.out.println("   "+ Thread.currentThread().getName() + ":  ,  "+val1+"~"+val2+"   ");
        long t1 = System.currentTimeMillis();
        sum();
        long t2 = System.currentTimeMillis();
        time = t2 - t1;
        System.out.println("   "+ Thread.currentThread().getName() + ":  ,    "+time+"ms");
        return sum;
    }

    public long getTime() {
        return time;
    }

    public void setTime(long time) {
        this.time = time;
    }

}

Main.java:
public class Main {

    public static void main(String[] args) throws InterruptedException, ExecutionException {

            Factorial c = new Factorial(1,10);
            FutureTask result = new FutureTask(c);
            new Thread(result).start();

            Factorial c2 = new Factorial(11,20);
            FutureTask result2 = new FutureTask(c2);
            new Thread(result2).start();

            long a = (long) result.get();
            long b = (long) result2.get();

            System.out.println("sum : "+(a*b));
    }

}