import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class ThreadPoolTest {
static BlockingQueue<Runnable> workQueue = new LinkedBlockingDeque<>();
static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2,5,3,TimeUnit.SECONDS,workQueue);
public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy()); //拒绝策略
List<Message> list = new ArrayList<>();
Future<Boolean>[] futures = new Future[20];
int i = 0;
Message msg = new Message("nihao","12346");
for(int x=0;x<10;x++) {
list.add(msg);
}
for(Message message : list){
Future<Boolean> submit = threadPoolExecutor.submit(message);
futures[i++] = submit;
}
//得到返回值,get方法会阻塞线程,所以设置过期时间
for(Future<Boolean> future : futures){
if(future == null){
return;
}
System.out.println(future.get(2, TimeUnit.SECONDS));
}
}
}
class Message implements Callable<Boolean>{
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
String word;
String target;
public Message(String word, String target) {
this.word = word;
this.target = target;
}
@Override
public Boolean call() throws Exception {
boolean flag = send(word,target);
return flag;
}
public boolean send(String word,String target){
System.out.println(word + " " + target);
return true;
}
}
只是对代码的分析
public boolean send(String word,String target){
System.out.println(word + " " + target);
return true;
}
每执行一次进行输出,也就是“nihao 123456”,返回true
//得到返回值,get方法会阻塞线程,所以设置过期时间
for(Future<Boolean> future : futures){
if(future == null){
return;
}
System.out.println(future.get(2, TimeUnit.SECONDS));
}
这里输出true
Message msg = new Message("nihao","12346");
for(int x=0;x<10;x++) {
list.add(msg);
}
这里通过循环创建了10个