Javase: Multithreading Supplement--thread communication

Source: Internet
Author: User

Thread communication I think it's the hardest part of multi-threading, and here are two examples to illustrate it.
The first one:
Use two threads to print 1-100. Thread 1, thread 2 alternating print

 Public  class Print implements Runnable{    inti =1; Public void Run(){ while(true){synchronized( This){if(i< -) {notify (); System.out.println (Thread.CurrentThread (). GetName () +":"+ i); i++;Try{Wait (); }Catch(Exception e)                    {System.out.println (E.getmessage ()); }                   }Else{ Break; }            }        }    }}
publicstaticvoidmain(String[] args){    new Print();    new Thread(p);    new Thread(p);    t1.start();    t2.start();}

A second example:
Producer Consumers:
The producer (productor) gives the product to the clerk (clerk), and the consumer (customer) takes the product from the clerk and the clerk can only hold a fixed number of products at a time (e.g. 20),
If the producer tries to produce more products, the clerk will call the producer to stop, if there is a vacancy in the store and then inform the producer to continue production;
If there is no product in the store, the clerk will tell the consumer to wait, if there is a product in the store and then notify the consumer to take away the product.

Problem Analysis:
1. is multithreading involved? Yes, producers and consumers
2. Is there a multithreaded synchronization involved? Yes, producer consumers manipulate shared data
3. are wired communication? Is.

 Public  class productor implements Runnable{Clerk Clerk =NULL;//To ensure that the object is a shared data, when it creates an object, it passes the same clerk object to it     Public Productor(Clerk Clerk) { This. Clerk = Clerk; } Public void Run(){//Unlimited production of products        //Do you think it is right to write the production directly here?         //write directly here, unable to manipulate the shared data. So we just let clerk add products to the good.          while(true){//If there is a problem, we enlarge the problem.             Try{Thread.currentThread.sleep (Ten); }Catch(Exception e) {                ......            }//Do you remember what I said yesterday? This sleep is written here must be handledClerk.addproduct (); }    }}

The same consumer I will not write in detail, and the same as above.

publicclass Consumer implements Runnable{    ......    publicvoidrun(){    ....    clerk.getProduct();    }}

To write the Clerk class:

 Public  class clerk{    intProduct//This is the shared data we are working on     Public synchronized void addproduct(){if(Product >= -){Try{Wait ();//production of more than 20, we wait for consumers to take away the reproduction}Catch(){                ....            } }Else{System.out.println (Thread......getname () +"Production of a product, now a total"+ Product +"a");            product++; Notify ();//Maybe this time, because there is no product, the consumer is waiting, we produce the product, we wake it up, we can take it away. }    }//Similar to the above ....      Public synchronized void getproduct(){if(Product <=0) {wait (); ......        }Else{            ......        } }}

Test Class I will not write, you can try it yourself.

So far, the review of multithreading is over, what we need to learn is to deal with multi-threaded ideas, as I have said above.
When the problem is not obvious, we can enlarge the problem by using the sleep () method.
But when we are dealing with this kind of problem, we can delete these irrelevant things. Focus on the nature of the problem, such as whether there are cross-sharing data, deadlock and other issues.
Also, pay attention to understanding the thread's life cycle. Well, that's the problem.
Tomorrow to review reflections, and write a report on my graduation project.

Javase: Multithreading Supplement--thread communication

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.