Multithreading-producers and consumers (storing data and printing data)

Source: Internet
Author: User

Wireless Path synchronization:

To store data:

1  Public classStorage {2     intdata;3 4      Public intGetData () {5         returndata;6     }7 8      Public  voidSetData (intdata) {9          This. data =data;Ten     } One  A}

Generate Data:

1  Public classCounterImplementsRunnable {2     PrivateStorage Storage;3 4      PublicCounter (Storage Storage) {5          This. Storage =storage;6     }7 8     intCount = 0;9 Ten @Override One      Public voidrun () { A          while(true) { -  - Storage.setdata (count); theSystem.out.println ("Storage Data set:" +count); -  -             Try { -Thread.Sleep ((int) (Math.random () * 1000)); +}Catch(interruptedexception e) { -  + e.printstacktrace (); A             } atcount++; -         } -  -     } -  -}

Read data:

1  Public classPrinterextendsThread {2     PrivateStorage Storage;3 4      PublicPrinter (Storage Storage) {5          This. Storage =storage;6     }7 8      Public voidrun () {9          while(true) {Ten  OneSystem.out.println ("Storage data print:" +storage.getdata ()); A  -             Try { -Thread.Sleep ((int) (Math.random () * 1000)); the}Catch(interruptedexception e) { -  - e.printstacktrace (); -             } +  -         } +  A     } at  -}

Test class:

1  Public classTestprint {2 3      Public Static voidMain (string[] args) {4Storage Storage =NewStorage ();5 6Counter Counter =NewCounter (storage);7Thread Th1 =NewThread (counter);8 9Printer Th2 =NewPrinter (storage);Ten Th1.start (); One Th2.start (); A     } -  -}

Operation Result:

Analysis of running results can be found two questions 1, producer resources may not be obtained by consumers 2, producers of resources may be repeated by consumers cause these problems because two threads do not consider synchronization control when accessing the same object. When consumers do not have access to resources, producers may have created new resources to make consumers miss some resources when a producer has not yet generated new resources, the consumer executes the Get () method again, causing the resource to be repeatedly fetched the key to solving the aforementioned problem is to introduce synchronization control logic between threads, by synchronizedKeyword lock Shared object method name before adding synchronized keyword tag with synchronized (object) {...} Tag locked code when a thread executes code that is controlled by the Synchronized keyword, the shared object is locked. If the other thread needs to manipulate the object, it must wait for the thread to finish executing the protected code modifications:
1  Public classStorage {2     intdata;3     Private Booleangetable;4 5      Public synchronized intGetData () {6          while(Getable = =false) {7             Try {8 wait ();9}Catch(interruptedexception e) {Ten e.printstacktrace (); One             } A         } -Getable =false; - Notifyall (); the         returndata; -     } -  -      Public synchronized voidSetData (intdata) { +  -          while(Getable = =true) { +             Try { A wait (); at}Catch(interruptedexception e) { -             } -         } -          This. data =data; -Getable =true; - Notifyall (); in     } -  to}

Operation Result:

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.