其他分享
首页 > 其他分享> > Callable 实现多线程

Callable 实现多线程

作者:互联网

package com.cj.java1;


import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

//1.创建类实现Callable
public class NumThread implements Callable {
    //实现call
    public Object call() throws Exception {
        int sum = 0;
        for (int i = 0; i <=100; i++) {
            sum+=i;
            System.out.println(sum);
        }
        return sum;
    }
}
class Test1{
    public static void main(String[] args) {
        NumThread numThread = new NumThread();
        FutureTask futureTask = new FutureTask(numThread);
        new Thread(futureTask).start();
        try {
            Object num = futureTask.get();
            System.out.println("总和:"+num);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }
}

 

标签:util,java,实现,Callable,concurrent,int,import,多线程
来源: https://www.cnblogs.com/cciscc/p/16094123.html