Java thread Synchronization Instance analysis _java

Source: Internet
Author: User
Tags modifier sleep

The examples in this article describe the use of Java thread synchronization. Share to everyone for your reference. The specific analysis is as follows:

The use of multithreading for our program provides a lot of convenience, but it also brings us to the past has not considered the trouble. An unexpected occurrence occurs when we use multithreading to handle shared resources: for example, we go out to dinner together, everyone is a thread, the food on the table is a shared resource, when I saw the red chicken leg on the table immediately after picking up the chopsticks straight to the target, watching the successful time, suddenly ~ ~ ~ Chicken Legs disappeared, A thread closer to the plate was gnawing proudly.

To avoid this problem, Java provides us with the "synchronized (sync) modifier" to avoid resource conflicts, you can declare a function or variable in the resource class as synchronized (synchronized), Each class that inherits from object contains a lock, which is the same for the rest of the life, and does not require writing any code to enable it. When we call any synchronized function, the object is locked, and all synchronized (synchronized) functions in the object cannot be invoked until the first function completes and unlocks the machine.

Import Java.awt.BorderLayout;
Import java.awt.event.ActionEvent;
Import Java.awt.event.ActionListener;
Import Javax.swing.JButton;
Import Javax.swing.JFrame;
Import Javax.swing.JPanel;
Import Javax.swing.JScrollPane;
Import Javax.swing.JTextArea;
Import Javax.swing.JTextField; 
 /** * Thread Synchronization * We simulate a bank stored procedure to prove the necessity of thread synchronization and the method of thread synchronization in Java * Focus: Synchronized modifier/public class TestMain5 extends JFrame { Private myaccounts myaccounts = null; My account is private jtextfield text = null; The amount of bank deposits shows private jtextarea textArea = null; The transaction process displays the private JButton button = null;
  Start the simulation of the trade button/** * Constructs a bank deposit and withdrawal Interface * * * public TestMain5 () {super ("Thread sync Test");
  myaccounts = new Myaccounts (); Text = new JTextField (integer.tostring (Myaccounts.inquire ()), 10);
  Our initial deposit in the bank is TextArea = new JTextArea ();
  Textarea.settext ("Transaction log:");
  JScrollPane sp = new JScrollPane (TextArea);
  button = new JButton ("Start transaction"); Button.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) {New Bank ("Bell tower Branch", Myaccounts, Bank.deal_saving, 800);
    New Bank ("Hi-tech sub-branch", Myaccounts, bank.deal_saving, 1300);
    New Bank ("Xiao Zhai sub-branches", Myaccounts, Bank.deal_fetch, 200);
    New Bank ("Yanta sub-branch", Myaccounts, Bank.deal_fetch, 400);
    New Bank ("Hing Qing Branch", Myaccounts, bank.deal_saving, 100);
   New Bank ("Earth Gate Branch", Myaccounts, Bank.deal_fetch, 700);
  }
  });
  JPanel pane = new JPanel ();
  Pane.add (text);
  Pane.add (button);
  This.getcontentpane (). Add (pane, Borderlayout.north);
  This.getcontentpane (). Add (SP);
  This.setdefaultcloseoperation (Jframe.exit_on_close);
  This.setsize (300, 200);
  This.setlocationrelativeto (NULL);
 This.setvisible (TRUE);
   /** * Bank Trading Floor class * General banks will have n trading floors, these halls can handle multiple business at the same time, this is just in line with the characteristics of multithreading/class Bank extends thread{/** * static field: Used to represent storage
  * * public static final int deal_saving = 0;
  /** * static field: Used to represent the extraction */public static final int deal_fetch = 1; private int buy = Bank.deal_fetch;
  Default to make withdrawals private int count = 0; Private Myaccounts myaccounts = Null My Account/** * Constructs this bank's trading floor * @param name This trading floor names * @param myaccounts my bank account * @param buy behavior, reference field: deal_saving or Deal_fetch * @param the quantity of Count money */public Bank (String name, myaccounts myaccounts, int buy, int count) {super (n
   AME);
   This.myaccounts = myaccounts;
   This.buy = buy;
   This.count = count;
  This.start ();
   public void Run () {int $count = 0;
   if (buy = = bank.deal_saving) {//If the deposit business $count = myaccounts.saving (count);
   }else if (buy = = Bank.deal_fetch) {//If it is a withdrawal business $count = Myaccounts.fetch (count);
   } text.settext (Integer.tostring ($count)); Textarea.append ("\ n" + this.getname () + "" + (Buy = = bank.deal_saving?)
  Deposit ":" withdrawal ") +" Amount: "+ Count +" balance: "+ $count);
  /** * My account * to sync Test/class myaccounts{private Integer count = 1100;
   Public myaccounts () {}/** * query my account */public int inquire () {synchronized (count) {return count; }/** * Deposit business * @param C deposit * @return BusinessThe quantity after the completion of the transaction/public int saving (int c) {synchronized (count) {//return count = C;//For better observation, we'll comment out this concise statement int $count = inquire ();
    First, check the deposit in the account $count + C;
    try {thread.sleep (1000);//For better observation, make the business stop here for 1 seconds} catch (Interruptedexception ex) {ex.printstacktrace (); Count = $count; Finally, the total is stored up return inquire (); Return the most recent deposits}/** * Withdrawal business * @param c Withdrawal quantity * @return The number of transactions completed after the completion of the business/public int fetch (int c) {synch  Ronized (count) {//return count = C;//For better observation, we annotate this concise statement with int $count = inquire ();//Check the deposit in the account $count-=
    C
    try {thread.sleep (1000);//For better observation, make the business stop here for 1 seconds} catch (Interruptedexception ex) {ex.printstacktrace (); Count = $count; Finally, the total is stored up return inquire ();
 Returns the most recent deposits}} public static void Main (String [] args) {new TestMain5 ();

 }
}

I hope this article will help you with your Java programming.

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.