Java core programming-thread thread pool (executorservice) (iv)

Source: Internet
Author: User

1. Background generated by the thread pool

Web services, database access, and so on are required to process a large number of request threads, if each time a new thread is created for each request, the task completes the destruction of the thread, for the server, the creation and destruction of the thread for the resource consumption is relatively large. Therefore, in order to prevent the waste of resources, the thread must be managed. The thread pool is the advanced technique for managing threads.

2. Function of thread pool

2.1 Through the management of the thread, more reasonable and efficient use of resources.

2.2 By maintaining the thread pool, you can save the overhead of creating threads.

3. Use of the thread pool

 PackageSe.thread;ImportJava.util.Random;ImportJava.util.concurrent.Executor;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors; Public classTreadpooltestextendsThread { Public Static voidMain (string[] args) {treadpooltest treadpooltest=Newtreadpooltest ();    Treadpooltest.start (); } @Override Public voidrun () {Executorservice Executorservice= Executors.newfixedthreadpool (2);  for(inti = 0; I < 100; i++) {Runnable Runnable=NewRunnable () {@Override Public voidrun () {LongTime = (Long) (Math.random () *1000); System.out.println ("Rest Time:" +time+ "MS"); Try{thread.sleep (time); } Catch(interruptedexception e) {e.printstacktrace ();            }                }            };        Executorservice.execute (runnable);    } executorservice.shutdown (); }}

Note: 1. The thread pool must be closed using the shutdown display.

2. In the For loop, it is common to wait for the thread pool to be idle, causing the main thread to block, so the for loop is generally put into the thread for it to run.

Java core programming-thread thread pool (executorservice) (iv)

Related Article

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.