IT干货网

用Callable创建线程

developer 2022年03月12日 编程设计 170 0

用Callable创建线程

创建线程的办法除了继承Thread类和实现Runnable接口,还有实现Callable接口。

以下代码演示使用Callable接口:

package com.cxf.multithread.collable; 
 
import java.util.concurrent.*; 
 
public class TestForCallable { 
    public static void main(String[] args) throws ExecutionException, InterruptedException { 
        MyJob thread = new MyJob(); 
        ExecutorService service = Executors.newFixedThreadPool(1);  // execute service,number of threads = 1 
        Future<Boolean> result = service.submit(thread);  // submit to execute 
        boolean r = result.get();  // get result 
        service.shutdownNow();  // shut down the service 
        System.out.println(r); 
 
    } 
} 
 
class MyJob implements Callable{ 
 
    @Override 
    public Boolean call() throws Exception { 
        for (int i = 0; i < 5; i++) { 
            System.out.println("I am running thread"); 
        } 
        return true; 
    } 
} 
 

输出结果:

I am running thread 
I am running thread 
I am running thread 
I am running thread 
I am running thread 
true 

用Callable创建线程时,需要

1.在call方法中写需要执行的任务,

2.创建执行服务,

3.提交线程到服务,

4.获取线程返回值,

5.关闭执行服务。


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

多线程模拟龟兔赛跑