首页 > 代码库 > 线程池的使用
线程池的使用
/* * 实现java.util.concurrent.Callable接口的类,可以被线程执行,并且还可以返回值 * 返回String */ public class Demo_04ThreadCallable implements Callable<String> { ?public String call() { ??System.out.println("实现Callable接口的线程实现"); ??return "abc"; ?} }
public class Demo_02Runnable implements Runnable { ?public void run() { ??System.out.println(Thread.currentThread().getName() + " 线程池"); ?} }
public class Demo_03Thread { ?public static void main(String[] args) throws Exception { ??ExecutorService service = Executors.newFixedThreadPool(2); ??// 提交线程,实现Callable接口实现类对象, submit返回 Future接口的实现类对象 ??Future<String> f = service.submit(newDemo_04ThreadCallable()); ??// 调用Future接口的实现类对象方法 get ??String s = f.get(); ??System.out.println(s);
??// submit可以提交Runnable接口的实现类,获取返回值,但是, run方法,void ??Future f1 = service.submit(new Runnable() { ???public void run() { ???} ??});
??System.out.println(f1.get()); ?} }
|
线程池的使用