When a novice Java programmer learns a thread, he or she wants to use multiple threads, either inheriting the thread class or implementing the Runnable interface and committing it to a newly created thread.
The following describes the use of Threadpoolexecutor thread performers to run multithreaded tasks. It separates the thread creation from the task run.
Package Test;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Java.util.concurrent.timeunit;public class Threadexecuteexample {public static void main (string[] args) { Executorservice service = Executors.newfixedthreadpool (2); for (int i = 0; i <; i++) {Service.execute (new runnabl E () {@Overridepublic void run () {try {thread.sleep (1 *);} catch (Interruptedexception e) {e.printstacktrace ();}});} Service.shutdown (); try {service.awaittermination (integer.max_value, timeunit.days);} catch (Interruptedexception e) {E.printstacktrace ();}}}
Executorservice service = Executors.newfixedthreadpool (2);
A Executorservice object with two threads was created through executors.
for (int i = 0; i < i++) {Service.execute (new Runnable () {@Overridepublic void run () {try {thread.sleep (1 * 1000);} catch (Interruptedexception e) {e.printstacktrace ();}}});}
10 instances of a Runnable object were submitted to Executorservice. The Executorservice uses the internal 2 threads to run the 10 runnable objects one after the other.
Service.shutdown ();
Close the performer. Because Executorservice uses its internal initialized threads to perform multiple runnable tasks that are committed, these threads are reused and not extinct. If the call shutdown () method is not displayed, the thread inside the Executorservice will survive, so that the virtual machine will not exit even if the task is completed. Calling shutdown () notifies Executorservice to destroy all threads after the task has run out.
Shutdown is a non-blocking method.
Service.awaittermination (Integer.max_value, timeunit.days);
Blocks waiting for the Executorservice task to complete within the specified time.
Performing tasks with thread performers