标签:返回值 cep err oid executor 继承 返回 exception call
1.继承Thread类
public class myThread extends Thread{
@Override
public void run() {
System.out.println("现在的线程是:"+Thread.currentThread());
}
public static void main(String[] args) {
new myThread().start();
new myThread().start();
new myThread().start();
}
}
2.实现Runnable接口
public class myRunnable implements Runnable{
@Override
public void run() {
System.out.println("现在的线程是:"+Thread.currentThread());
}
public static void main(String[] args) {
new Thread(new myRunnable()).start();
new Thread(new myRunnable()).start();
new Thread(new myRunnable()).start();
}
}
3.实现Callable接口并用FutureTask包装
public class MyCallAble implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("现在的线程是:"+Thread.currentThread());
return null;
}
public static void main(String[] args) {
new Thread(new FutureTask<>(new MyCallAble())).start();
new Thread(new FutureTask<>(new MyCallAble())).start();
new Thread(new FutureTask<>(new MyCallAble())).start();
new Thread(new FutureTask<>(new MyCallAble())).start();
new Thread(new FutureTask<>(new MyCallAble())).start();
}
}
4.利用Executor类返回的线程
public class ExcutorPool {
public static void main(String[] args) throws Exception{
ExecutorService pool = Executors.newFixedThreadPool(10);
List<Future<Integer>> list=new ArrayList<Future<Integer>>();
for (int i = 0; i < 10; i++) {
Future<Integer> future=pool.submit(new Callable<Integer>() {
public Integer call() throws Exception {
System.out.println("当前线程为"+Thread.currentThread());
return null;
}
});
list.add(future);
}
//关闭线程池
pool.shutdown();
for (Future<Integer> future : list) {
//此处输出线程结束后的返回值future.get();
}
}
}
标签:返回值 cep err oid executor 继承 返回 exception call
原文地址:https://www.cnblogs.com/xujuntao/p/12372488.html