public class MyThread implements Callable<String> {
private String name;
private int waittime;
@Override
public String call() throws Exception {
log.info("mythread "+name+" start running" );
if(waittime !=0)
Thread.sleep(waittime);
log.info("mythread "+name+" stop running" );
return name;
}
}
线程池
static ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
@Test
public void TestPollCallable(){
List<MyThread> myThreadList = new ArrayList<>();
for(int i=0;i<10;i++)
{
MyThread myThread = new MyThread("wait"+i,5000);
myThreadList.add(myThread);
}
List <Future> futures = new ArrayList<>();
myThreadList.stream().forEach(tr-> futures.add(fixedThreadPool.submit(tr)));
futures.stream().forEach(future-> System.out.println("thread return "+future.get()));
}
callable
@Test
public void TestCallabe() throws ExecutionException, InterruptedException {
MyThread myThread = new MyThread("wait10",3000); //
FutureTask<String> result = new FutureTask<String>(myThread);
new Thread(result).start();
System.out.println("thread return"+ result.get());
}
线程池1
static final ExecutorService THREAD_POOL= Executors.newFixedThreadPool(10);
@Test
public void contextLoads() throws ExecutionException, InterruptedException {
FutureTask<String> resultaaatask = new FutureTask<>(new Callable<String>() {
@Override
public String call() throws Exception {
log.info("start callablea");
sleep(1000);
return "hello aaa";
}
});
FutureTask<String> resultbbbtask = new FutureTask<>(()->{
log.info("start callableb");
sleep(2000);
return "hello bbb";
}
);
THREAD_POOL.submit(resultaaatask);
THREAD_POOL.submit(resultbbbtask);
String retval = resultaaatask.get();
String retvalb = resultbbbtask.get();
log.info("retval:"+retval+" "+retvalb);
}