C/C++教程

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();
        }

    }
}

 

这篇关于Callable 实现多线程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!