JAVA concurrent programming-sharing data between multiple threads (vi)

Source: Internet
Author: User
Tags ticket


how to share data in multiple threads:

1 , if each thread executes the same code, you can use the same Runnable object, this Runnable The object has that shared data, for example, a ticket-selling system can do so.

2 , if each thread executes a different code, it needs to use a different Runnable object, for example, to design 4 threads. Of these, two threads add 1 to J at a time, and two threads to J each minus 1, bank deposit and withdrawal

There are two ways to solve this type of problem:

The shared data is encapsulated into another object, which is then passed to each Runnable object one by one, and each thread assigns the method of the shared data to that object, which makes it easy to implement mutual exclusion and communication for each operation of the data.

The Runnable object is used as the inner class of a class, and the shared data acts as a member variable for the class, and each thread also encapsulates the external class for the operation method of the shared data in order to achieve synchronization and mutual exclusion for each operation of the data, and to invoke these methods of the outer classes as individual runnable objects of the inner class.

The following describes

Each thread executes the same code and can use the same Runnable Object

Ticket Selling System Demo :


Package com.tgb.hjy;/** * Multi-threaded shared data-ticketing system * @author Hejingyuan * */public class Sellticket {/**      * @param args      */
   
    public static void Main (string[] args) {          Ticket t = new Ticket ();          New Thread (t). Start ();          New Thread (t). Start ();      }  } Class Ticket implements runnable{        private int Ticket = ten;      public void Run () {          while (ticket>0) {              ticket--;              System.out.println ("The current number of votes is:" +ticket);}                }    
   



Simple multi-threaded data sharing, each thread executes different code, with different Runnable objects

Design 4 threads.


Of these, two threads each add 1 to J, and the other two threads to J each minus 1


Package Com.tgb.hjy;public class Testthread {/**      * @param args      *      /public static void main (string[] args) {
   final MyData data = new MyData ();          for (int i=0;i<2;i++) {              new Thread (new Runnable () {public                    void run () {                      data.add ()}                            }). Start ();              New Thread (New Runnable () {public                                 void run () {                      data.dec ();                                    }                            }). Start ();}}    } Class MyData {      private int j=0;      Public  synchronized void Add () {          j + +;          SYSTEM.OUT.PRINTLN ("Thread" +thread.currentthread (). GetName () + "J for:" +j);      }      Public  synchronized void Dec () {          j--;          SYSTEM.OUT.PRINTLN ("Thread" +thread.currentthread (). GetName () + "J for:" +j);      }  }  



example of bank deposit and withdrawal:

Package Com.tgb.hjy;public class Acount {private int money, public acount (int money) {This.money=money;} Public synchronized void Getmoney (int money) {//Note this place must be in the while loop, because even if you deposit money again it may be less than the take (This.money<money) {Syste   M.out.println ("Withdrawal:" +money+ "Balance:" +this.money+ "balance is insufficient, waiting for deposit ...");  try{wait ();} catch (Exception e) {}} This.money=this.money-money;  System.out.println ("Take Out:" +money+ "also remaining:" +this.money); } public synchronized void Setmoney (int. money) {try{thread.sleep (10);}  catch (Exception e) {} This.money=this.money+money;  System.out.println ("New Deposit:" +money+ "total:" +this.money); Notify ();  } public static void Main (String args[]) {acount acount=new acount (0);  Bank B=new Bank (acount);  Consumer c=new Consumer (acount);  New Thread (b). Start (); New Thread (c). Start (); }}//Deposit Class Bank implements Runnable {acount acount;public Bank (acount acount) {this. Acount=acount;} public void Run () {while (true) {int temp= (int) (Math.random () *1000); Acount.setmoney (temp); }}}//Withdrawal Classes Class ConSumer implements Runnable {acount acount;public Consumer (acount acount) {this. Acount=acount;} public void Run () {while (true) {int temp= (int) (Math.random () *1000); Acount.getmoney (temp);}}}




Summary:

In fact, multi-threaded shared data is the main mutex, multiple threads share a variable, for the operation of the variable to achieve atomicity.




Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

JAVA concurrent programming-sharing data between multiple threads (vi)

Related Article

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.