Concurrent processing of Java. util. Concurrent package)

Source: Internet
Author: User
We all know that before jdk1.5, when Java needs to implement business concurrency, programmers usually need to implement Code independently. When designing high quality Java multi-thread concurrent programs, to prevent the appearance of such phenomena as death, such as using wait (), Y (), and synchronized before Java, every time you need to consider performance, deadlock, fairness, resource management, and how to avoid the harm caused by thread security, some complicated security policies are often used, increases the development burden of programmers. fortunately, after the emergence of jdk1.5, Sun finally launched Java for our poor programmers. util. concurrent toolkit to simplify concurrency. With this, developers can effectively reduce race conditions and deadlock threads. The concurrent package solves these problems and provides us with a more practical concurrent program model.

Main interfaces and classes in Java. util. Concurrent:

Executor: executor of a specific runnable task.

Executorservice: A thread pool manager, whose implementation classes include common thread pools and regular scheduling thread pools scheduledexecutorservice.

Runnable and callable are submitted to the pool for scheduling.

Future: it is an interface that interacts with runnable and callable. For example, a thread obtains the returned results after execution ends, and a cancel termination thread is also provided.

Blockingqueue: blocking the queue.

Below is a simple example program:

Futureproxy. JavaView copies to clipboard Printing

  1. Package org. Test. Concurrent;
  2. /***//**
  3. * <P> title: loonframework </P>
  4. * <P> Description: Processing in future mode </P>
  5. * <P> copyright: Copyright (c) 2007 </P>
  6. * <P> company: loonframework </P>
  7. * @ Author chenpeng
  8. * @ Email: ceponline@yahoo.com.cn
  9. * @ Version 0.1
  10. */
  11. Import java. Lang. Reflect. invocationhandler;
  12. Import java. Lang. Reflect. method;
  13. Import java. Lang. Reflect. proxy;
  14. Import java. util. Concurrent. callable;
  15. Import java. util. Concurrent. executorservice;
  16. Import java. util. Concurrent. executors;
  17. Import java. util. Concurrent. Future;
  18. Import java. util. Concurrent. threadfactory;
  19. Public abstract class futureproxy <t> {
  20. Private final class callableimpl implements callable <t> {
  21. Public t call () throws exception {
  22. Return futureproxy. This. createinstance ();
  23. }
  24. }
  25. Private Static class invocationhandlerimpl <t> implements invocationhandler {
  26. Private future <t> future;
  27. Private volatile t instance;
  28. Invocationhandlerimpl (Future <t> future ){
  29. This. Future = future;
  30. }
  31. Public object invoke (Object proxy, method, object [] ARGs)
  32. Throws throwable {
  33. Synchronized (this ){
  34. If (this. Future. isdone ()){
  35. This. instance = This. Future. Get ();
  36. } Else {
  37. While (! This. Future. isdone ()){
  38. Try {
  39. This. instance = This. Future. Get ();
  40. } Catch (interruptedexception e ){
  41. Thread. currentthread (). Interrupt ();
  42. }
  43. }
  44. }
  45. Return method. Invoke (this. instance, argS );
  46. }
  47. }
  48. }
  49. /***//**
  50. * Implement the java. util. Concurrent. threadfactory Interface
  51. * @ Author chenpeng
  52. *
  53. */
  54. Private Static final class threadfactoryimpl implements threadfactory {
  55. Public thread newthread (runnable R ){
  56. Thread thread = new thread (R );
  57. Thread. setdaemon (true );
  58. Return thread;
  59. }
  60. }
  61. Private Static executorservice service = executors. newcachedthreadpool (New threadfactoryimpl ());
  62. Protected abstract t createinstance ();
  63. Protected abstract class <? Extends T> getinterface ();
  64. /***//**
  65. * Returns the proxy instance.
  66. * @ Return
  67. */
  68. @ Suppresswarnings ("unchecked ")
  69. Public final t getproxyinstance (){
  70. Class <? Extends T> interfaceclass = This. getinterface ();
  71. If (interfaceclass = NULL |! Interfaceclass. isinterface ()){
  72. Throw new illegalstateexception ();
  73. }
  74. Callable <t> task = new callableimpl ();
  75. Future <t> future = futureproxy. Service. Submit (task );
  76. Return (t) proxy. newproxyinstance (interfaceclass. getclassloader (),
  77. New Class <?> [] {Interfaceclass}, new invocationhandlerimpl (Future ));
  78. }
  79. }
Package Org. test. concurrent;/*** // *** <p> title: loonframework </P> * <p> description: processing in future mode </P> * <p> copyright: Copyright (c) 2007 </P> * <p> company: loonframework </P> * @ author chenpeng * @ Email: ceponline@yahoo.com.cn * @ version 0.1 */import Java. lang. reflect. invocationhandler; import Java. lang. reflect. method; import Java. lang. reflect. proxy; import Java. util. concurrent. callable; import Java. util. conc Urrent. executorservice; import Java. util. concurrent. executors; import Java. util. concurrent. future; import Java. util. concurrent. threadfactory; public abstract class futureproxy <t> {private final class callableimpl implements callable <t> {public t call () throws exception {return futureproxy. this. createinstance () ;}} Private Static class invocationhandlerimpl <t> implements invocationhandler {private Future <t> future; private volatile t instance; invocationhandlerimpl (Future <t> future) {This. future = Future;} public object invoke (Object proxy, method, object [] ARGs) throws throwable {synchronized (this) {If (this. future. isdone () {This. instance = This. future. get ();} else {While (! This. future. isdone () {try {This. instance = This. future. get ();} catch (interruptedexception e) {thread. currentthread (). interrupt () ;}} return method. invoke (this. instance, argS) ;}}/ ***** // *** implement Java. util. concurrent. threadfactory interface * @ author chenpeng */Private Static final class threadfactoryimpl implements threadfactory {public thread newthread (runnable R) {thread = new thread (R ); Thread. setdaemon (true); Return thread ;}} Private Static executorservice service = executors. newcachedthreadpool (New threadfactoryimpl (); protected abstract t createinstance (); protected abstract class <? Extends T> getinterface ();/*** // *** return proxy instance * @ return */@ suppresswarnings ("unchecked") Public final t getproxyinstance () {class <? Extends T> interfaceclass = This. getinterface (); If (interfaceclass = NULL |! Interfaceclass. isinterface () {Throw new illegalstateexception ();} callable <t> task = new callableimpl (); Future <t> future = futureproxy. service. submit (task); Return (t) proxy. newproxyinstance (interfaceclass. getclassloader (), new class <?> [] {Interfaceclass}, new invocationhandlerimpl (Future ));}}

Test. JavaView copies to clipboard Printing

  1. Package org. Test. Concurrent;
  2. Import java. util. calendar;
  3. /***//**
  4. * <P> title: loonframework </P>
  5. * <P> Description: </P>
  6. * <P> copyright: Copyright (c) 2007 </P>
  7. * <P> company: loonframework </P>
  8. * @ Author chenpeng
  9. * @ Email: ceponline@yahoo.com.cn
  10. * @ Version 0.1
  11. */
  12. Interface datetest {
  13. String getdate ();
  14. }
  15. Class datetestimpl implements datetest {
  16. Private string _ date = NULL;
  17. Public datetestimpl (){
  18. Try {
  19. _ Date + = calendar. getinstance (). gettime ();
  20. // Set the latency of five seconds
  21. Thread. Sleep (5000 );
  22. } Catch (interruptedexception e ){
  23. }
  24. }
  25. Public String getdate (){
  26. Return "date" + _ date;
  27. }
  28. }
  29. Class datetestfactory extends futureproxy <datetest> {
  30. @ Override
  31. Protected datetest createinstance (){
  32. Return new datetestimpl ();
  33. }
  34. @ Override
  35. Protected class <? Extends datetest> getinterface (){
  36. Return datetest. Class;
  37. }
  38. }
  39. Public class test {
  40. Public static void main (string [] ARGs ){
  41. Datetestfactory factory = new datetestfactory ();
  42. Datetest [] DTS = new datetest [100];
  43. For (INT I = 0; I <DTS. length; I ++ ){
  44. DTS [I] = factory. getproxyinstance ();
  45. }
  46. // Execute Traversal
  47. For (datetest DT: DTS ){
  48. System. Out. println (Dt. getdate ());
  49. }
  50. }
  51. }

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.