package method;
import java.util.concurrent.Callable;
/**
* 功能描述: 多线程处理
*/
public class ThreadsImpl implements Callable{
private String str1;
private String str2;
public ThreadsImpl(String str1,String str2){
super();
this.str1=str1;
this.str2=str2;
}
@Override
public String call() throws Exception {
String str=str1+str2;
System.out.println("ThreadsImpl:"+str);
return str;
}
}
==================================================================
package method;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* 功能描述: 多线程处理
*/
public class ThreadsService {
private static final int TIMEOUT = 10;
public static void main(String[] args) throws TimeoutException {
List<Future> futureList = new ArrayList<Future>();
// 通过线程池管理,开启2个线程执行任务
ExecutorService exeSer = Executors.newFixedThreadPool(2);// 方法1,控制启线程的个数
ExecutorService exeSer1 = Executors.newSingleThreadScheduledExecutor();// 方法1,不控制启线程的个数
ThreadsImpl strThread = new ThreadsImpl("a", "b");// 执行逻辑部分
Future fut = exeSer.submit(strThread);// 开启线程,返回的是future
futureList.add(fut);// 收集返回接口
List<String> list = new ArrayList<String>();
for (Future future : futureList) {
try {
String result = (String) future.get();// 方法1
String result1 = (String) future.get(TIMEOUT, TimeUnit.MILLISECONDS);// 方法2,有时间限制
list.add(result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
System.out.println(list);
}
}