Java multithreading (2)

Source: Internet
Author: User

Thread coordination

In Java multithreading, you can use the synchronized modifier to modify the instance resources shared between threads to synchronize between threads. In addition, the coordination between threads must be considered in the multi-threaded design. A typical design pattern for coordination is the Producer-Consumer) pattern. Producer-Consumer) Mode

In this mode, there are two types of threads: Producer and Consumer. The Producer thread is used to generate Data sharing Data resources), and the Consumer thread is used to consume Data between Producer and Consumer, there is a coordination between Data generation and consumption, that is, when there is no Data, the Consumer thread needs to wait for the Producer thread to generate new Data, and when there are too many Data, the Producer thread needs to wait for the Consumer thread to consume too much Data. In the Producer-Consumer mode, Channel pipelines are introduced to coordinate Data among various threads. The following figure shows the UML class diagram of the Producer-Consumer mode.

650) this. width = 650; "style =" width: 553px; height: 290px "border =" 0 "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/1225103957-0.jpg "width =" 583 "height =" 317 "/>

In, both the Producer Thread class and the Consumer Thread class contain references to Channel class objects, while Channel class objects encapsulate Data classes, the synchronous methods of production and consumption Data are also implemented, namely, produce and consume. In the produce and consume methods, Data coordination is further achieved by using the wait and notifyAll methods.

  Wait, policy, and policyallIn Java, wait, policy, and policyall are Object-class methods used to pause and wake up threads that call Object methods. Wait is used to suspend a thread and put it into the wait set thread of the object to wait for the set). The Y and yyall methods are used to wake up the thread in the wait set and keep it running. Notify and policyall are different. When there are multiple threads in the wait set, notify will only wake up one thread at random, while notifyAll will wake up all threads from them for competition, obtain the synchronization lock and continue execution.

A simple example of using wait, policy, and policyall.

650) this. width = 650; "border =" 0 "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/1225104000-1.jpg "width =" 614 "height =" 382 "/>

Implementation example of the Producer-Consumer Mode

Producer and Consumer thread classes
 
 
  1. Package com. wt. pc;
  2.  
  3. Public class Producer extends Thread {
  4.  
  5. // Reference the Channel object
  6. Channel channel = null;
  7. // Consumer Constructor
  8. Public Producer (String producerName, Channel channel)
  9. {
  10. Super (producerName );
  11. This. channel = channel;
  12. }
  13. // The Producer thread attempts to generate new data every MS
  14. Public void run ()
  15. {
  16. Try {
  17. While (true)
  18. {
  19. Channel. produce (Integer. toString (Channel. dataId ++ ));
  20. Thread. sleep (500 );
  21. }
  22. } Catch (Exception e ){}
  23. }
  24. }
 
 
 
  1. Package com. wt. pc;
  2.  
  3. Public class Consumer extends Thread {
  4.  
  5. // Reference the Channel object
  6. Channel channel = null;
  7. // Consumer Constructor
  8. Public Consumer (String consumerName, Channel channel)
  9. {
  10. Super (consumerName );
  11. This. channel = channel;
  12. }
  13. // The Consumer thread tries to consume data every MS
  14. Public void run ()
  15. {
  16. Try {
  17. While (true)
  18. {
  19. Channel. consume ();
  20. Thread. sleep (500 );
  21. }
  22. } Catch (Exception e ){}
  23. }
  24.  
  25. }
Channel and Data class
 
 
  1. Package com. wt. pc;
  2.  
  3. Public class Channel {
  4. // Static variable used to generate the data name
  5. Static int dataId = 0;
  6. // Data storage array
  7. Data dataList [];
  8. // The sequence number of the currently unconsumed data Header
  9. Int head;
  10. // The next end number of the currently unconsumed data
  11. Int tail;
  12. // Number of data not consumed currently
  13. Int count;
  14. // Channel Constructor
  15. // The array capacity is 3, and other values are initialized to 0.
  16. Public Channel ()
  17. {
  18. DataList = new Data [3];
  19. Head = 0;
  20. Tail = 0;
  21. Count = 0;
  22. }
  23.  
  24. // The produce method for generating data
  25. Public synchronized void produce (String dataName) throws Exception {
  26. // When the array capacity is full, that is, when the new data cannot be regenerated, the current thread enters the wait set
  27. While (count> = 3)
  28. {
  29. Wait ();
  30. }
  31. // Generate new data
  32. System. out. println (Thread. currentThread (). getName () + "is producing" + dataName );
  33. DataList [tail] = new Data ();
  34. DataList [tail]. setDataName (dataName );
  35. Tail = (tail + 1) % 3;
  36. Count ++;
  37. Thread. sleep (400 );
  38. // Wake up the thread in the wait set
  39. Policyall ();
  40. }
  41. // Consume method, used to consume data
  42. Public synchronized void consume () throws Exception {
  43. // When the array capacity is empty, that is, when data cannot be consumed, the current thread enters the wait set
  44. While (count <= 0)
  45. {
  46. Wait ();
  47. }
  48. // Consume data
  49. System. out. println (Thread. currentThread (). getName () + "is consuming" + dataList [head]. getDataName ());
  50. Head = (head + 1) % 3;
  51. Count --;
  52. Thread. sleep (300 );
  53. // Wake up the thread in the wait set
  54. Policyall ();
  55. }
  56. }
 
 
 
  1. package com.wt.pc;  
  2. public class Data {  
  3.     String dataName;  
  4.  
  5.     public String getDataName() {  
  6.         return dataName;  
  7.     }  
  8.  
  9.     public void setDataName(String dataName) {  
  10.         this.dataName = dataName;  
  11.     }  
  12. }  
Main Function
 
 
  1. public static void main(String args[])  
  2. {  
  3.     Channel channel = new Channel();  
  4.     new Producer("p1",channel).start();  
  5.     new Producer("p2",channel).start();  
  6.     new Producer("p3",channel).start();  
  7.     new Consumer("c1",channel).start();  
  8.     new Consumer("c2",channel).start();  
  9.     new Consumer("c3",channel).start();  
  10.       
  Execution result
P2 is producing 0
C2 is consuming 0
P3 is producing 2
P1 is producing 1
C3 is consuming 2
C1 is consuming 1
P1 is producing 5
P3 is producing 4
C2 is consuming 5
P2 is producing 3
P3 is producing 7
C1 is consuming 4
C3 is consuming 3
P3 is producing 9
P1 is producing 6
C2 is consuming 7
P2 is producing 8
C3 is consuming 9
C1 is consuming 6
P2 is producing 12
P3 is producing 10
C2 is consuming 8
......
From the execution results, we can see that the number of executions of the generated Data thread p and the number of executions of the consumption Data thread c always meet the following requirements: p> = c and p <= c + 3 ensure that the Data array has Data but does not exceed the array capacity during consumption, so as to effectively implement Data coordination between the Producer and Consumer thread classes. Summary

In Java multithreading design, synchronization and coordination between threads must be fully considered. Different design modes can be used for different application scenarios, existing design modes include Single Threaded Execution, Immutable, Guarded Suspension, Balking, Producer-Consumer, Read-Write Lock, Thread-Per-Message, and Worker Thread, for details, refer to the "Java multithreading design mode" tutorial on the Internet.

This article is from the "Learning document" blog, please be sure to keep this source http://zephiruswt.blog.51cto.com/5193151/937337

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.