ExecutorService test

package t1;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestThread13 {

public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
List<Future<String>> resultList = new ArrayList<Future<String>>();
for (int i = 0; i < 10; i++) {
Future<String> future = executorService.submit(new TaskWithResult(i));
resultList.add(future);
}
executorService.shutdown();

for (Future<String> future : resultList) {
try {
System.out.println("************" + future.get());
} catch (Exception e) {
executorService.shutdownNow();
return;
}
}
}
}

class TaskWithResult implements Callable<String> {
private int id;

public TaskWithResult(int id) {
this.id = id;
}

// specific process tasks, task once passed ExecutorService the submit method, the method is automatically executed on a thread.
@Override
public String Call () throws Exception {
System.out.println ( "Call () method is invoked automatically, tasks" + Thread.currentThread () getName ().);
. IF (new new the Random () nextBoolean () )
the throw new new TaskException ( "error in task Meet" + Thread.currentThread () getName ());.
(int I = 999999999 for; I> 0; I ++)
;
return "call () method is automatically invoked, the task results is: "+ ID +" "+ Thread.currentThread () getName ();.
}
}

class TaskException extends Exception {
public TaskException(String msg) {
super(msg);
}
}

The results uncertain:

 

Guess you like

Origin www.cnblogs.com/dengw125792/p/12605167.html