java实现线程的4种方式--实现Callable接口

 

 

package com.LearnJava.Thread;

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

class numThread implements Callable {

    @Override
    public Object call () {
        int sum =0;
        for(int i=0;i<100;i++){
            if(i%2==0){
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                sum+=i;
            }
        }
        return sum;

    }
}
public class ThreadTest3 {
    public static void main(String[] args) {
        numThread nt = new numThread();

        FutureTask f = new FutureTask(nt);

        new Thread(f){}.start();

        try {
            Object sum = f.get();
            System.out.println(sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

 

posted @ 2020-02-08 19:35  超级学渣渣  阅读(982)  评论(0编辑  收藏  举报