How to implement multithreading three:
A: Create a thread pool object that controls the creation of several thread objects.
public static Executorservice newfixedthreadpool (int nthreads)
B: Do a class to implement the callable interface.
C: Call the following method to
Future<?> Submit (Runnable Task)
<T> future<t> Submit (callable<t> Task)
D: I'm going to end it, okay?
OK.
Packagecom.test;Importjava.util.concurrent.Callable; Public classMycallableImplementsCallable<integer> { Private intNumber ; PublicMycallable (intNumber ) { This. Number =Number ; } @Override PublicInteger Call ()throwsException {intsum = 0; for(intx=1;x<=number;x++) {sum+=x; } returnsum; }}
Packagecom.test;Importjava.util.concurrent.ExecutionException;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.Future; Public classCallabletest { Public Static voidMain (string[] args)throwsinterruptedexception, executionexception {/**To create a thread pool object*/Executorservice Pool= Executors.newfixedthreadpool (2); /**can execute Runnable object or thread represented by callable object*/ Future<Integer> f1 = Pool.submit (NewMycallable (100)); Future<Integer> F2 = Pool.submit (NewMycallable (200)); /**V get ()*/Integer I1=F1.get (); Integer I2=F2.get (); System.out.println (I1); System.out.println (I2); /**End*/Pool.shutdown (); }}
Operation Result:
505020100
"Multithreading implementation Scenario three: Implementing Callable Interface"