Java multithreading ~~~ Use ThreadPoolExecutor to create a thread

Source: Internet
Author: User

Java multithreading ~~~ Use ThreadPoolExecutor to create a thread

Previously, when we created a Thread, we actively added a new Thread and then called their start method. However, if there are many threads

In many cases, writing will be very troublesome. Of course, the efficiency may not be very high. Java provides us with a class called the thread generator concept,

He can help us manage these threads. What you do is to write the code and hand it over to him, and she will automatically help you run it.

Of course, the threadpool with cache will provide excellent performance for re-calling dead threads, but too many threads cannot be handed in.

Manage it for him. Otherwise, the system will be dragged down. Let's take an example.

package com.bird.concursey.charpet6;import java.util.Date;import java.util.concurrent.TimeUnit;public class Task implements Runnable {// store the creation date of the taskprivate Date initDate;// store the name of the taskprivate String name;public Task(String name) {this.initDate = new Date();this.name = name;}@Overridepublic void run() {System.out.printf("%s: Task %s: Created on: %s\n", Thread.currentThread().getName(), name, initDate);System.out.printf("%s: Task %s: Started on: %s\n", Thread.currentThread().getName(), name, new Date());try {Long duration = (long) (Math.random() * 10);System.out.printf("%s: Task %s: Doing a task during %d seconds\n",Thread.currentThread().getName(), name, duration);TimeUnit.SECONDS.sleep(duration);} catch (InterruptedException e) {e.printStackTrace();}System.out.printf("%s: Task %s: Finished on: %s\n",Thread.currentThread().getName(),name,new Date());}}

Package com. bird. concursey. charpet6; import java. util. concurrent. executors; import java. util. concurrent. threadPoolExecutor;/*** execute every task it processes es using an executor ** @ author bird 9:03:01, January 1, September 23, 2014 */public class Server {threadprivate poolexecutor executor; public Server () {executor = (ThreadPoolExecutor) Executors. newCachedThreadPool ();} public void executeTask (Task task) {System. out. printf ("Server: A new task has arrived \ n" cannot executor.exe cute (task); System. out. printf ("Server: Pool Size: % d \ n", executor. getPoolSize (); System. out. printf ("Server: Active Count: % d \ n", executor. getActiveCount (); System. out. printf ("Server: Completed Tasks: % d \ n", executor. getCompletedTaskCount ();} public void endServer () {executor. shutdown ();} public static void main (String [] args) {Server server = new Server (); for (int I = 0; I <100; I ++) {Task task = new Task ("Task" + imo-server.exe cuteTask (task);} server. endServer ();}}


If a large number of threads enter, it will create an object for each thread, which will overload the system. Executors provides a constructor

Set the maximum number of threads. If the number of created threads exceeds this number, Executors will not create this thread again, waiting

After the threads are running, the system will be able to create new threads after they are idle. This will make the system more robust.


This is not required for the above Code. We only need to instantiate a code in the constructor.

public Server() {executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);}


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.