Java thread synchronization instance analysis

  • 2020-04-01 04:00:22
  • OfStack

This article illustrates the use of Java thread synchronization as an example. Share with you for your reference. Specific analysis is as follows:

The use of multithreading provides a lot of convenience for our program, but it also brings us trouble that we have not considered before. When we use multithreading Shared resource accident will happen: such as we dine out together, everyone is a single thread, food on the table is a Shared resource, when I saw the braised chicken leg on the table immediately after picked up the chopsticks straight, watched the successful time, suddenly disappeared ~ ~ ~ chicken legs, a thread is plate closer satisfiedly nibbled.

In order to avoid these problems, Java provides us with the synchronized modifier (synchronization) "to avoid resource conflict, you can use the resource class a function or variable declarations for synchronized (synchronization), each inherited from the Object class contains a machine Lock (Lock), it is the rest of your life by, does not need to write any code to enable it. When we call any synchronized function, the object is locked, and all synchronized functions in the object cannot be called until the first function is executed and the lock is unlocked.


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;

public class TestMain5 extends JFrame {
 private MyAccounts myAccounts = null; //My account
 private JTextField text = null; //The amount of bank deposits is shown
 private JTextArea textArea = null; //Trading process display
 private JButton button = null; //Button to start simulating a trade
 
 public TestMain5(){
  super(" Thread synchronization test ");
  myAccounts = new MyAccounts();
  text = new JTextField(Integer.toString(myAccounts.inquire()), 10); //Our initial deposit in the bank was 100
  textArea = new JTextArea();
  textArea.setText(" Transaction log: ");
  JScrollPane sp = new JScrollPane(textArea);
  button = new JButton(" Start trading ");
  button.addActionListener(new ActionListener(){
   public void actionPerformed(ActionEvent e) {
    new Bank(" The clock tower sub-branch ", myAccounts, Bank.DEAL_SAVING, 800);
    new Bank(" High and new branches ", myAccounts, Bank.DEAL_SAVING, 1300);
    new Bank(" Small village branch ", myAccounts, Bank.DEAL_FETCH, 200);
    new Bank(" Wild goose tower sub-branch ", myAccounts, Bank.DEAL_FETCH, 400);
    new Bank(" Xingqing branch ", myAccounts, Bank.DEAL_SAVING, 100);
    new Bank(" The soil door 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);
 }
 
 class Bank extends Thread{
  
  public static final int DEAL_SAVING = 0;
  
  public static final int DEAL_FETCH = 1;
  private int buy = Bank.DEAL_FETCH; //Default withdrawal
  private int count = 0;
  private MyAccounts myAccounts = null; //My account
  
  public Bank(String name, MyAccounts myAccounts, int buy, int count){
   super(name);
   this.myAccounts = myAccounts;
   this.buy = buy;
   this.count = count;
   this.start();
  }
  public void run(){
   int $count = 0;
   if(buy == Bank.DEAL_SAVING){ //If it's a deposit business
    $count = myAccounts.saving(count);
   }else if(buy == Bank.DEAL_FETCH){ //If it's a withdrawal business
    $count = myAccounts.fetch(count);
   }
   text.setText(Integer.toString($count));
   textArea.append("n" + this.getName() + " " + (buy == Bank.DEAL_SAVING ? " deposit ": " withdrawals ") + "  Amount: " + count + "  Balance: " + $count);
  }
 }
 
 class MyAccounts{
  private Integer count = 1100;
  public MyAccounts(){
  }
  
  public int inquire(){
   synchronized (count){
    return count;
   }
  }
  
  public int saving(int c){
   synchronized (count){
    //return count += c; //  For a better look, let's comment out this neat statement 
    int $count = inquire(); //Check the account first
    $count += c;
    try {
     Thread.sleep(1000); //For a better view, let the business pause here for 1 second
    } catch (InterruptedException ex) {
     ex.printStackTrace();
    }
    count = $count; //Finally, store the total
    return inquire(); //Returns the latest deposit
   }
  }
  
  public int fetch(int c){
   synchronized (count){
    //return count -= c; //  For a better look, let's comment out this neat statement 
    int $count = inquire(); //Check the account first
    $count -= c;
    try {
     Thread.sleep(1000); //For a better view, let the business pause here for 1 second
    } catch (InterruptedException ex) {
     ex.printStackTrace();
    }
    count = $count; //Finally, store the total
    return inquire(); //Returns the latest deposit
   }
  }
 }
 public static void main(String [] args){
  new TestMain5();
 }
}

I hope this article has been helpful to your Java programming.


Related articles: