代码示例:
package cn.zxj.th;
import java.util.concurrent.Callable;
public class MyCall implements Callable{
@Override
public Object call() throws Exception {
for(int i = 0;i<10;i++){
System.out.println(Thread.currentThread().getName()+" "+(i+1));
}
return null;
}
}
package cn.zxj.th;
public class MyRun implements Runnable{
@Override
public void run() {
for(int i = 0;i<10;i++){
System.out.println(Thread.currentThread().getName()+" "+(i+1));
}
}
}
package cn.zxj.th;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolDemo {
public static void main(String[] args){
ExecutorService executorService = Executors.newFixedThreadPool(2);
//调用Runnable run
Runnable runnable = new MyRun();
executorService.submit(runnable);
executorService.submit(runnable);
//调用Callable call
Callable callable = new MyCall();
executorService.submit(callable);
executorService.submit(callable);
executorService.shutdown();
}
}