Java executors (thread pool)

Source: Internet
Author: User

Sun in the JAVA5, the Java thread of the class library to do a lot of expansion, in which the thread pool is one of the new features of JAVA5, in addition to the thread pool, there are many multi-threaded related content, for multi-threaded programming has brought great convenience. In order to write high-performance and stable and reliable multithreaded programs, the new content of the thread part is particularly important.

The contents of the JAVA5 line assigns feature are all under Java.util.concurrent, which contains a number of interfaces and classes, and familiarity with this part of the API feature is a difficult learning process. At present, the information and books on this aspect are few and far between, and the book on the thread of the big belongs to the knowledge level before Java5.

Of course, the new features do not have a need for long-line programs, before JAVA5 General can write excellent multi-threaded program. But the price is different.

The basic idea of the thread pool is also the idea of an object pool, which opens up a memory space in which many (not dead) threads are stored, and the thread execution schedule is handled by the pool manager. When a thread task is taken from a pool, the threads object is pooled after execution, which avoids the performance overhead of repeatedly creating thread objects and saves system resources.

Before Java5, to implement a thread pool is quite difficult, now Java5 for us to do everything, we just need to follow the provided API to use, can enjoy the great convenience of the thread pool.

JAVA5 's thread pool can be divided into two categories: a fixed-size thread pool and a variable-size connection pool.

Before using the thread pool, you must know how to create a thread pool, and in Java5, you need to know about the API of the Java.util.concurrent.Executors class, which provides a lot of static methods for creating connection pools that you must master.

A fixed-size thread pool, Newfixedthreadpool:

[Java]View Plaincopy
  1. Package app.executors;
  2. Import java.util.concurrent.Executors;
  3. Import Java.util.concurrent.ExecutorService;
  4. /**
  5. * Java Thread: thread pool
  6. *
  7. * @author Feng Xiaowei
  8. */
  9. Public class Test {
  10. public static void Main (string[] args) {
  11. //Create a thread pool that can reuse a fixed number of threads
  12. Executorservice pool = Executors.newfixedthreadpool (5);
  13. //Create thread
  14. Thread T1 = new MyThread ();
  15. Thread t2 = new MyThread ();
  16. Thread t3 = new MyThread ();
  17. Thread T4 = new MyThread ();
  18. Thread T5 = new MyThread ();
  19. //Put the thread into the pool for execution
  20. Pool.execute (t1);
  21. Pool.execute (T2);
  22. Pool.execute (T3);
  23. Pool.execute (T4);
  24. Pool.execute (T5);
  25. //close thread pool
  26. Pool.shutdown ();
  27. }
  28. }
  29. Class MyThread extends Thread {
  30. @Override
  31. public Void Run () {
  32. System.out.println (Thread.CurrentThread (). GetName () + "executing ...  ");
  33. }
  34. }


Output Result:

[HTML]View Plaincopy
    1. Pool-1-thread-1 is executing ...
    2. Pool-1-thread-3 is executing ...
    3. Pool-1-thread-4 is executing ...
    4. Pool-1-thread-2 is executing ...
    5. Pool-1-thread-5 is executing ...


Change the parameters in Executorservice pool = Executors.newfixedthreadpool (5): Executorservice pool = Executors.newfixedthreadpool (2), The output is:

[HTML]View Plaincopy
    1. Pool-1-thread-1 is executing ...
    2. Pool-1-thread-1 is executing ...
    3. Pool-1-thread-2 is executing ...
    4. Pool-1-thread-1 is executing ...
    5. Pool-1-thread-2 is executing ...


As can be seen from the above results, the Newfixedthreadpool parameter specifies the maximum number of threads that can be run, which will not run after the number of lines loads in. Second, threads that join the thread pool are managed, and the threads are not affected by the order of accession.

Second, single task thread pool, Newsinglethreadexecutor:

Just change the Executorservice pool = Executors.newfixedthreadpool (2) in the above code to Executorservice pool = Executors.newsinglethreadexecutor ();

Output Result:

[HTML]View Plaincopy
    1. Pool-1-thread-1 is executing ...
    2. Pool-1-thread-1 is executing ...
    3. Pool-1-thread-1 is executing ...
    4. Pool-1-thread-1 is executing ...
    5. Pool-1-thread-1 is executing ...

As you can see, each call to the Execute method is, in fact, the last call to the Thread-1 run method.

Three, variable size thread pool, Newcachedthreadpool:

Similar to the above, just change the way the pool was created: executorservice pool = Executors.newcachedthreadpool ();


Output:

[HTML]View Plaincopy
    1. Pool-1-thread-1 is executing ...
    2. Pool-1-thread-2 is executing ...
    3. Pool-1-thread-4 is executing ...
    4. Pool-1-thread-3 is executing ...
    5. Pool-1-thread-5 is executing ...


This approach is characterized by the creation of thread pools for new threads as needed, but reusing them when previously constructed threads are available.

Iv. delayed Connection pool, Newscheduledthreadpool:

[Java]View Plaincopy
  1. Package app.executors;
  2. Import java.util.concurrent.Executors;
  3. Import Java.util.concurrent.ScheduledExecutorService;
  4. Import Java.util.concurrent.TimeUnit;
  5. /**
  6. * Java Thread: thread pool
  7. *
  8. * @author Feng Xiaowei
  9. */
  10. Public class Test {
  11. public static void Main (string[] args) {
  12. //Create a thread pool that can schedule commands to run after a given delay or perform them on a regular basis.
  13. Scheduledexecutorservice pool = Executors.newscheduledthreadpool (2);
  14. //created implements the Runnable interface object, the thread object of course also implements the Runnable interface
  15. Thread T1 = new MyThread ();
  16. Thread t2 = new MyThread ();
  17. Thread t3 = new MyThread ();
  18. //Put the thread into the pool for execution
  19. Pool.execute (t1);
  20. //Using the method of deferred execution style
  21. Pool.schedule (T2, timeunit.milliseconds);
  22. Pool.schedule (T3, ten, timeunit.milliseconds);
  23. //close thread pool
  24. Pool.shutdown ();
  25. }
  26. }
  27. Class MyThread extends Thread {
  28. @Override
  29. public Void Run () {
  30. System.out.println (Thread.CurrentThread (). GetName () + "executing ...  ");
  31. }
  32. }


Readers can try to change the parameters of Executors.newscheduledthreadpool (2) to get more experience, of course, let

[Java]View Plaincopy
    1. @Override
    2. Public void Run () {
    3. System.out.println (Thread.CurrentThread (). GetName () + "executing ...  ");
    4. }

into an infinite loop, you can get more usage about Pool.shutdown ().

V: Single-task delayed connection pool (similar to the above, it is not written). Of course, we can also customize the thread pool, here will not write, tired ah ...

Transferred from: http://blog.csdn.net/coding_or_coded/article/details/6856014

Java executors (thread pool)

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.