Callable与Runnable

/**

  • Callable与Runnable功能相似,Callable的call有返回值
  • 可以返回给客户端,而Runnable没有返回值,一般情况下,Callable
  • 与FutureTask一起使用,或者通过线程池的submit方法返回相应的Future
  • Future就是对于具体的Runnable或者Callable任务的执行结果进行取消,
  • 查询是否完成,获取结果,设置结果操作。get方法会阻塞,直到任务返回结果
  • FutureTask则是一个RunnableFuture,而RunnableFuture实现了Runnable又
  • 实现了Futrue这两个接口
    */

1.Runable()

public class ThreadPoolDemo {

public static void main(String[] args)
{
    LinkedBlockingQueue objects = new LinkedBlockingQueue<>();

    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10,20,3,TimeUnit.SECONDS,objects);
    //100个任务
    for(int i = 0 ; i<100; i++)
    {
        threadPoolExecutor.submit(()->{
            System.out.println(Thread.currentThread().getName());
        });
    }
}

2.Callable

public class CallableDemo implements Callable {

@Override
public String call() throws Exception {
    Thread.sleep(3000);
    return "111";
}


public static void main(String[] args) throws Exception{
    CallableDemo callableDemo = new CallableDemo();
    FutureTask stringFutureTask = new FutureTask<>(callableDemo);
    new Thread(stringFutureTask).start();
    System.out.println(stringFutureTask.get());
}

}

2.1

public class ThreadPoolDemoPlusCallable {

/**
 * 希望获取到每个线程返回一个结果就用 Callable
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception
{
    LinkedBlockingQueue objects = new LinkedBlockingQueue<>();

    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10,20,3,TimeUnit.SECONDS,objects);
    Future submit = null;
    //100个任务
    for(int i = 0 ; i<100; i++)
    {
        submit = threadPoolExecutor.submit(new CallableDemo());
    }

    for(int i = 0 ; i<100; i++)
    {
        System.out.println(submit.get());
    }
}

}

}

你可能感兴趣的:(线程)