用Executor来构建线程池,应该要做的事:
1).调用Executors类中的静态方法newCachedThreadPool(必要时创建新线程,空闲线程会被保留60秒)或newFixedThreadPool(包含固定数量的线程池)等,返回的是一个实现了ExecutorService接口的ThreadPoolExecutor类或者是一个实现了ScheduledExecutorServiece接口的类对象。
2).调用submit提交Runnable或Callable对象。
3).如果想要取消一个任务,或如果提交Callable对象,那就要保存好返回的Future对象。
4).当不再提交任何任务时,调用shutdown方法。
举2个例子如下:
package thread.test04;
import java.util.concurrent.*;
public class ThreadTestA {
public static void main(String[] args) {
ExecutorService e=Executors.newFixedThreadPool(10);
e.execute(new MyRunnableA());
e.execute(new MyRunnableB());
e.shutdown();
}
}
class MyRunnableA implements Runnable{
public void run(){
System.out.println("Runnable:run()....");
int i=0;
while(i<20){
i++;
for(int j=0;j<1000000;j++);
System.out.println("i="+i);
}
}
}
class MyRunnableB implements Runnable{
public void run(){
char c='A'-1;
while(c<'Z'){
c++;
for(int j=0;j<1000000;j++);
System.out.println("c="+c);
}
}
}
package thread.test04;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ThreadTestB {
public static void main(String[] args) {
ExecutorService e=Executors.newFixedThreadPool(10);
Future f1=e.submit(new MyCallableA());
Future f2=e.submit(new MyCallableA());
Future f3=e.submit(new MyCallableA());
Future f4=e.submit(new MyCallableA());
Future f5=e.submit(new MyCallableA());
System.out.println("--Future.get()....");
try {
System.out.println(f1.get());
System.out.println(f2.get());
System.out.println(f3.get());
System.out.println(f4.get());
System.out.println(f5.get());
} catch (InterruptedException e1) {
e1.printStackTrace();
} catch (ExecutionException e1) {
e1.printStackTrace();
}
e.shutdown();
}
}
class MyCallableA implements Callable<String>{
public String call() throws Exception {
System.out.println("开始执行Callable");
String[] ss={"zhangsan","lisi"};
long[] num=new long[2];
for(int i=0;i<1000000;i++){
num[(int)(Math.random()*2)]++;
}
if(num[0]>num[1]){
return ss[0];
}else if(num[0]<num[1]){
throw new Exception("弃权!");
}else{
return ss[1];
}
}
}