JDK 1.5 uses java. util. concurrent to develop concurrent applications

Source: Internet
Author: User

Simple concurrent applications

A new package is added to the JDK 1.5 API.

Java. util. Concurrent is a commonly used Utility Class in concurrent programming.
Java. util. Concurrent. Locks provides a framework interface and class for locking and waiting conditions, which is different from built-in synchronization and monitoring.

Class Diagram under this package

 

Common classes:

Executors provides a method to establish a thread pool or thread factory.

Executorservice provides a way to manage termination and generate a future for tracking the execution of one or more asynchronous tasks.

Executor can be simply understood as the executor of a thread.

Future indicates the result of asynchronous calculation. The execution result can be obtained by checking the status of the executed thread.

FutureTask provides the basic implementation of Future. You can use FutureTask to wrap Callable or Runnable objects. Therefore, you can submit FutureTask to Executor for execution.

Interface to be implemented by the Callable thread

Semaphore is a counting Semaphore, which is usually used to limit the number of threads that can access certain resources (physical or logical.

For more details about the application of classes and methods, refer to the API

The following is a simple example:

(Limit the number of concurrent threads)

  1. Public
     
    Static
     
    Void
    Main (String [] args ){

  2. // Thread Pool
  3. ExecutorService exec = Executors. newCachedThreadPool ();

  4. // Only five threads can simultaneously access

  5. Final
    Semaphore semp =
    New
    Semaphore (
    5
    );

  6. // Simulate access from 20 clients

  7. For
    (
    Int
    Index =
    0
    ; Index <
    20
    ; Index ++ ){

  8. Final
     
    Int
    NO = index;
  9. Runnable run =
    New
    Runnable (){

  10. Public
     
    Void
    Run (){

  11. Try
    {

  12. // Obtain the license
  13. Semp. acquire ();
  14. System. out. println (
    "Thread :"
    + NO );
  15. Thread. sleep ((
    Long
    ) (Math. random ()*
    1000
    ));

  16. // Release after access
  17. SEMP. Release ();
  18. }
    Catch
    (Interruptedexception e ){
  19. }
  20. }
  21. };
  22. Exec.exe cute (run );
  23. }

  24. // Exit the thread pool
  25. Exec. shutdown ();
  26. }

 

Simple thread pool management:

  1. Import
    Java. util. concurrent. Callable;
  2. Import
    Java. util. concurrent. ExecutionException;
  3. Import
    Java. util. concurrent. ExecutorService;
  4. Import
    Java. util. concurrent. Executors;
  5. Import
    Java. util. concurrent. Future;
  6. Import
    Java. util. concurrent. FutureTask;
  7. Import
    Java. util. concurrent. Semaphore;
  8. /**
     
  9. * Management class of Thread Pool
     
  10. * Obtain such instances through static methods
     
  11. */

  12. Public
     
    Class
    ThreadPoolManager <T> {

  13. Private
    ExecutorService service =
    Null
    ;

  14. Private
     
    Final
    Semaphore semp;

  15. Private
     
    Int
    MaxNum =
    3
    ;

  16. Private
     
    Static
    ThreadPoolManager me =
    Null
    ;

  17. Public
     
    Static
    ThreadPoolManager getInstance (){

  18. If
    (Me =
    Null
    ){
  19. Me =
    New
    ThreadPoolManager ();
  20. }

  21. Return
    Me;
  22. }

  23. Public
     
    Static
    ThreadPoolManager getInstance (
    Int
    MaxNum ){

  24. If
    (Me =
    Null
    ){
  25. Me =
    New
    Threadpoolmanager (maxnum );
  26. }

  27. Return
    Me;
  28. }

  29. Private
    Threadpoolmanager (){
  30. Service = executors. newcachedthreadpool ();
  31. SEMP =
    New
    Semaphore (maxnum );
  32. }

  33. Private
    Threadpoolmanager (
    Int
    Maxnum ){

  34. This
    . Maxnum = maxnum;
  35. Service = executors. newcachedthreadpool ();
  36. SEMP =
    New
    Semaphore (maxnum );
  37. }

  38. /**
     
  39. * Executes a thread task and returns the result.
     
  40. * If the number of thread pools is all occupied, the thread is blocked.
     
  41. * The implementation method of the input parameter class for thread running.
     
  42. * @ Param task implement the java. util. concurrent. Callable Interface Class
     
  43. * @ Return returns the result of thread running.
     
  44. * @ Throws InterruptedException
     
  45. * @ Throws ExecutionException
     
  46. */


  47. Public
    T runTask (Callable <T> task)
    Throws
    InterruptedException, ExecutionException {
  48. Semp. acquire ();
    // Use signal flag. If the number is exceeded, thread blocking will occur.
  49. Future <t> F = service. Submit (task );
    // Load the thread task and execute
  50. SEMP. Release ();
    // Signal release

  51. Return
    F. Get ();
    // Return the processing result of the thread. If the processing is not completed, the thread is blocked until the returned result is returned.
  52. }

  53. /**
     
  54. * @ Return the number of available return threads
     
  55. */


  56. Public
     
    Synchronized
     
    Int
    Getavailablenum (){

  57. Return
     
    This
    . SEMP. availablepermits ();
  58. }

  59. /**
     
  60. * Close the thread pool.
     
  61. */


  62. Public
     
    Final
     
    Void
    Close (){
  63. Service. shutdown ();
  64. }
  65. }

 

Blog Source: http://ajava.org/course/java/12954.html

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.