Learning and understanding Java thread synchronization-producer and consumer example

Source: Internet
Author: User

Java thread synchronization usually requires the use of sychronized to lock critical resources. The so-called critical resources are the resources used by these threads.

Sychronized is usually placed before the method name, which indicates that the method is synchronized, and is actually locking this.

Alternatively, you can lock an object that is commonly used before an object.

The examples of producers and consumers are very classic. here we need to define a pool for putting products in. Define the producer to continuously produce products. If the pool is not satisfied, the producer can continue to store the product. If the pool is full, the producer will wait.

The consumer keeps retrieving data from the pool. If the pool is empty, the consumer waits.

We use runnable to implement producers and consumers.

Write a synchronization stack as a pool to synchronize the push and pop methods.
The Code is as follows:

Class sycnstack {private integer Index = 0; private char [] data; Public sycnstack (INT num) {DATA = new char [num];} public void push (char C) {synchronized (this) {// Why not lock the Index ??? Thiswhile (Index = data. Length-1) {system. Out. println ("the pool is full and cannot be placed! "+ Thread. currentthread (). tostring (); try {This. wait ();} catch (interruptedexception e) {e. printstacktrace () ;}} this. Y (); // obtain the lock data [Index] = C; system. out. println ("put in" + C + "" + thread. currentthread (). tostring (); index ++ ;}} public character POP () {synchronized (this) {While (Index = 0) {system. out. println ("the pool is empty and cannot be retrieved! "+ Thread. currentthread (). tostring (); try {This. wait ();} catch (interruptedexception e) {e. printstacktrace () ;}} this. Y (); index --; char c = data [Index]; system. out. println ("retrieve" + C + "" + thread. currentthread (). tostring (); Return C ;}}

Then write the producer and consumer, and the run method is to continuously put the production product into the pool or take out the product:

class Producer implements Runnable{private SycnStack stack;public Producer(SycnStack stack){this.stack = stack;}@Overridepublic void run() {int i=10;while(i-->0){stack.push( (char)(26*Math.random()+'A'));Thread.yield();}}}class Consumer implements Runnable{private SycnStack stack;public Consumer(SycnStack stack){this.stack = stack;}@Overridepublic void run() {int i=10;while(i-->0){stack.pop();Thread.yield();}}}

The main method is as follows: Create a stack to store the product, create a producer and consumer to use the stack, and start it:

public class ProductorConsumer {public static void main(String[] args){SycnStack s = new SycnStack(5);new Thread(new Producer(s)).start();new Thread(new Consumer(s)).start();}}

The result is as follows:

Put g thread [thread-0, 5, main], put l thread [thread-0, 5, main], and put D thread [thread-0, 5, put main] into k thread [thread-0, 5, main] The pool is full and cannot be put! Thread [thread-0, 5, main] Fetch K thread [thread-1, 5, main] and put it into P thread [thread-0, 5, main] The pool is full, it cannot be entered! Thread [thread-0, 5, main] Get P thread [thread-1, 5, main] and put it into E thread [thread-0, 5, main] The pool is full, it cannot be entered! Thread [thread-0, 5, main] to get e thread [thread-1, 5, main] and put it into M thread [thread-0, 5, main] The pool is full, it cannot be entered! Thread [thread-0, 5, main] Get m thread [thread-1, 5, main] and put it into P thread [thread-0, 5, main] The pool is full, it cannot be entered! Thread [thread-0, 5, main] Get P thread [thread-1, 5, main] and put it into q thread [thread-0, 5, main] The pool is full, it cannot be entered! Thread [thread-0, 5, main] Get Q thread [thread-1, 5, main] and put it into l thread [thread-0, 5, main] Fetch l thread [thread-1, 5, main] Fetch D thread [thread-1, 5, main] Fetch l thread [thread-1, 5, main] Fetch g thread [thread-1, 5, main]

The tenth line of the code for the synchronization stack is to lock this, which means to lock the current stack.

Previously I tried to lock the index and found an error. I think it may be because the critical resource is not only the index, but also the data. If I only lock the index, when a thread is using the stack, another thread can still use the stack, which will cause index confusion and report an error.

If anyone has a more detailed explanation, let me know.

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.