使用Callable及FutureTask创建一个能入参以及有返回参数的线程

package cbd.efficacy.user.test;

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


public class Test {
    public static CopyOnWriteArrayList arr=new CopyOnWriteArrayList();
    public static void main(String[] args) {
        arr.add("a");
        arr.add("b");
        arr.add("c");
        arr.add("d");
        arr.add("e");
        arr.add("f");
        Callable myCallable = new MyCallable(1);    // 创建MyCallable对象
        FutureTask ft = new FutureTask(myCallable); //使用FutureTask来包装MyCallable对象

        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + " " + i);
            if (i == 10) {
                Thread thread = new Thread(ft);   //FutureTask对象作为Thread对象的target创建新的线程
                thread.start();                      //线程进入到就绪状态
            }
        }

        System.out.println("主线程for循环执行完毕..");

        try {                              //调用get方法会阻塞主线程等待结果,不调用则不会阻塞
            int sum = ft.get();            //取得新创建的新线程中的call()方法返回的结果
            System.out.println("sum = " + sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }




}



 class MyCallable implements Callable {
    private int i ;

     public MyCallable(int i) {
         this.i = i;
     }

     // 与run()方法不同的是,call()方法具有返回值
    @Override
    public Integer call() {
        int sum = 0;
        for (; i < 6; i++) {
            System.out.println(Thread.currentThread().getName() + " ," + Test.arr.get(i));
            sum += 1;
        }
        return sum;
    }

}

你可能感兴趣的:(使用Callable及FutureTask创建一个能入参以及有返回参数的线程)