Learn java-17.2 basic threading mechanism from the beginning (2) use of-executors

Source: Internet
Author: User

In the previous chapters we are all directly managing thread, and here we explain another class executors that manages thread.

1. Example:

Package Com.ray.ch17;import Java.util.concurrent.countdownlatch;import Java.util.concurrent.ExecutorService; Import Java.util.concurrent.executors;public class Test {public static void main (string[] args) throws interruptedexception {Long startTime = System.currenttimemillis (); Executorservice Executorservice = Executors.newcachedthreadpool (); Countdownlatch Countdownlatch = new Countdownlatch (5); for (int i = 5; i <; i++) {donemission donemission = new Donem Ission (i, Countdownlatch); Executorservice.execute (donemission);} Executorservice.shutdown (); countdownlatch.await (); Long endTime = System.currenttimemillis (); System.out.println (); System.out.println (Endtime-starttime);}} Class Donemission implements Runnable {private final int id = index++;p rivate int count = 0;private static int index = 0;p Rivate countdownlatch countdownlatch;public donemission (int count, Countdownlatch countdownlatch) {this.count = count; This.countdownlatch = Countdownlatch;} Public String leftmission () {return ' #"+ ID +" ("+ Count +") ";} @Overridepublic void Run () {while (count--> 0) {System.out.print (leftmission ()); try {thread.sleep ()} catch ( Interruptedexception e) {e.printstacktrace ();} Thread.yield ();} Countdownlatch.countdown ();}}


Explain:

(1) The class that runs the task is basically consistent with the previous

(2) using Executors.newcachedthreadpool () to generate the thread pool, we can take it when the thread driver is needed, and the number of threads it generates is systematically controlled.


2. Control the number of threads

Package Com.ray.ch17;import Java.util.concurrent.countdownlatch;import Java.util.concurrent.ExecutorService; Import Java.util.concurrent.executors;public class Test {public static void main (string[] args) throws interruptedexception {Long startTime = System.currenttimemillis (); Executorservice Executorservice = Executors.newfixedthreadpool (5);//number of control threads countdownlatch Countdownlatch = new Countdownlatch (5); for (int i = 5; i < i++) {donemission donemission = new Donemission (i, countdownlatch); executorse Rvice.execute (donemission);} Executorservice.shutdown (); countdownlatch.await (); Long endTime = System.currenttimemillis (); System.out.println (); System.out.println (Endtime-starttime);}} Class Donemission implements Runnable {private final int id = index++;p rivate int count = 0;private static int index = 0;p Rivate countdownlatch countdownlatch;public donemission (int count, Countdownlatch countdownlatch) {this.count = count; This.countdownlatch = Countdownlatch;} Public String leftmission () {Return "#" + ID + "(" + Count + ")";} @Overridepublic void Run () {while (count--> 0) {System.out.print (leftmission ()); try {thread.sleep ()} catch ( Interruptedexception e) {e.printstacktrace ();} Thread.yield ();} Countdownlatch.countdown ();}}

The code above simply replaces the number of threads, but we generally recommend using the cache, because it optimizes the thread pool. Especially for short asynchronous tasks it has obvious advantages.


3. Test when the different threads run:

Package Com.ray.ch17;import Java.util.concurrent.countdownlatch;import Java.util.concurrent.ExecutorService; Import Java.util.concurrent.executors;public class Test {public static void main (string[] args) throws interruptedexception {Long startTime = System.currenttimemillis (); Executorservice Executorservice = Executors.newcachedthreadpool (); Countdownlatch Countdownlatch = new Countdownlatch (5); for (int i = 5; i <; i++) {donemission donemission = new Donem Ission (i, Countdownlatch); Executorservice.execute (donemission);} Executorservice.shutdown (); countdownlatch.await (); Long endTime = System.currenttimemillis (); System.out.println (); System.out.println ("Time:" + (Endtime-starttime));}} Class Donemission implements Runnable {private final int id = index++;p rivate int count = 0;private static int index = 0;p Rivate countdownlatch countdownlatch;public donemission (int count, Countdownlatch countdownlatch) {this.count = count; This.countdownlatch = Countdownlatch;} Public String leftmission (){return "#" + ID + "(" + Count + ")";} @Overridepublic void Run () {while (count--> 0) {System.out.print (leftmission ()); try {thread.sleep ()} catch ( Interruptedexception e) {e.printstacktrace ();} Thread.yield ();} Countdownlatch.countdown ();}}

Output:

#0 (4) #1 (5) #2 (6) #3 (7) #4 (8) #0 (3) #1 (4) #4 (7) #3 (6) #2 (5) #0 (2) #1 (3) #3 (5) #2 (4) #4 (6) #0 (1) #1 (2) #4 (5) #3 (4) #2 (3) #0 (0) #1 (1) #2 (2) #4 (4) #3 (3) #1 (0) #2 (1) #3 (2) #4 (3) #4 (2) #3 (1) #2 (0) #3 (0) #4 (1) #4 (0)
904


Control to 3 Threads:

Package Com.ray.ch17;import Java.util.concurrent.countdownlatch;import Java.util.concurrent.ExecutorService; Import Java.util.concurrent.executors;public class Test {public static void main (string[] args) throws interruptedexception {Long startTime = System.currenttimemillis (); Executorservice Executorservice = Executors.newfixedthreadpool (3); Countdownlatch Countdownlatch = new Countdownlatch (5); for (int i = 5; i <; i++) {donemission donemission = new Donem Ission (i, Countdownlatch); Executorservice.execute (donemission);} Executorservice.shutdown (); countdownlatch.await (); Long endTime = System.currenttimemillis (); System.out.println (); System.out.println (Endtime-starttime);}} Class Donemission implements Runnable {private final int id = index++;p rivate int count = 0;private static int index = 0;p Rivate countdownlatch countdownlatch;public donemission (int count, Countdownlatch countdownlatch) {this.count = count; This.countdownlatch = Countdownlatch;} Public String leftmission () {return ' #"+ ID +" ("+ Count +") ";} @Overridepublic void Run () {while (count--> 0) {System.out.print (leftmission ()); try {thread.sleep ()} catch ( Interruptedexception e) {e.printstacktrace ();} Thread.yield ();} Countdownlatch.countdown ();}}

Output:

#0 (4) #2 (6) #1 (5) #1 (4) #0 (3) #2 (5) #0 (2) #2 (4) #1 (3) #1 (2) #2 (3) #0 (1) #0 (0) #1 (1) #2 (2) #1 (0) #2 (1) #3 (7) #3 (6) #4 (8) #2 (0) #3 (5) #4 (7) #3 (4) #4 (6) #3 (3) #4 (5) #4 (4) #3 (2) #4 (3) #3 (1) #4 (2) #3 (0) #4 (1) #4 (0)
1504


Control to Single thread:

Package Com.ray.ch17;import Java.util.concurrent.countdownlatch;import Java.util.concurrent.ExecutorService; Import Java.util.concurrent.executors;public class Test {public static void main (string[] args) throws interruptedexception {Long startTime = System.currenttimemillis (); Executorservice Executorservice = Executors.newsinglethreadexecutor (); Countdownlatch Countdownlatch = new Countdownlatch (5); for (int i = 5; i <; i++) {donemission donemission = new Donem Ission (i, Countdownlatch); Executorservice.execute (donemission);} Executorservice.shutdown (); countdownlatch.await (); Long endTime = System.currenttimemillis (); System.out.println (); System.out.println (Endtime-starttime);}} Class Donemission implements Runnable {private final int id = index++;p rivate int count = 0;private static int index = 0;p Rivate countdownlatch countdownlatch;public donemission (int count, Countdownlatch countdownlatch) {this.count = count; This.countdownlatch = Countdownlatch;} Public String leftmission () {returN "#" + ID + "(" + Count + ")";} @Overridepublic void Run () {while (count--> 0) {System.out.print (leftmission ()); try {thread.sleep ()} catch ( Interruptedexception e) {e.printstacktrace ();} Thread.yield ();} Countdownlatch.countdown ();}}

Output:

#0 (4) #0 (3) #0 (2) #0 (1) #0 (0) #1 (5) #1 (4) #1 (3) #1 (2) #1 (1) #1 (0) #2 (6) #2 (5) #2 (4) #2 (3) #2 (2) #2 (1) #2 (0) #3 (7) #3 (6) #3 (5) #3 (4) #3 (3) #3 (2) #3 (1) #3 (0) #4 (8) #4 (7) #4 (6) #4 (5) #4 (4) #4 (3) #4 (2) #4 (1) #4 (0)
3503

A single thread is just as straightforward as using a for to run in the main method.


4. About Shutdown () (the following paragraph from the http://my.oschina.net/bairrfhoinn/blog/177639, I think he explained the more clearly, in fact, the key is the author is lazy, do not like typing)

In order to close the thread in Executorservice, you need to call the shutdown () method. Executorservice does not close immediately, but instead of receiving new tasks, Executorservie really shuts down once all the threads have finished executing the current task. All tasks that are committed to Executorservice before the shutdown () method is called will be executed.
If you want to close executorservice immediately, you can call the Shutdownnow () method. This method attempts to close all the tasks that are being performed immediately, and skips all tasks that have been committed but are not yet running. However, it is not guaranteed to be able to successfully shut down a task that is being performed, and it is possible that they have actually been shut down, or it may have been executed until the end of the task.


Summary: This chapter mainly introduces the use of executors.


This chapter is here, thank you.

-----------------------------------

Directory


Learn java-17.2 basic threading mechanism from the beginning (2) use of-executors

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.