Synchronized thread synchronization code and simple usage (to be supplemented)

① There are two threads: accounting and cashier, They share a book program to ensure that one of them when saveOrTake (int amount) use, will have to wait another person, namely saveOrTake (int amount) method should be a synchronized method .

running result:image

code show as below:

 

Bank categories:

public class Bank implements Runnable {
   int money=200;
   public void setMoney(int n) {
      money=n;
   }
   public void run() {
      if(Thread.currentThread().getName().equals("会计")) 
         saveOrTake(300);
      else if(Thread.currentThread().getName().equals("出纳"))
         saveOrTake(150);
   }
    public synchronized void saveOrTake(intAMOUNT) { // access method 
      IF (Thread.currentThread () getName () the equals ( "Accounting.". )) {
          for ( int I =. 1; I <=. 3; I ++ ) { 
             Money = Money AMOUNT + /. 3 ;       // each deposit amount / 3, receded about 
             System.out.println (Thread.currentThread () getName () +. 
                               "deposit" + amount / 3 + ", there is the account" + money + "million and the rest one will save " );
              the try {the Thread.sleep (1000);   // time cashier can not use the method saveOrTake 
             }                       
              the catch (InterruptedException E) {} 
         } 
      } 
      the else  IF(.. Thread.currentThread () getName ( ) equals ( " Teller" )) {
          for ( int I =. 1; I <=. 3; I ++) { // cashier removed using an access method 60 
             Money = Money-AMOUNT /. 3 ;    // each out amount / 3, receded about 
             System.out.println (Thread.currentThread () getName () +. 
                               "remove" + amount / 3 + "has the account" + money + "million and a rest and then take " );
              the try {the Thread.sleep (1000);        // time accounting method can not use saveOrTake 
             }                         
              the catch (InterruptedException E) {} 
         } 
      } 
   } 
}

TestBank categories:

public class TestBank{
   public static void main(String args[]) {
      Bank bank = new Bank();
      bank.setMoney(200);
      Thread accountant,    //会计
             cashier;      //出纳
      accountant = new Thread(bank);
      cashier = new Thread(bank);
      accountant.setName("会计");
      cashier.setName("出纳");
      accountant.start();
      cashier.start(); 
   }
}

②Synchronized keyword usage:

https://blog.csdn.net/weixin_41632656/article/details/79063503

(I am lazy, time must be summed up his own)

Guess you like

Origin www.cnblogs.com/jianqiao123/p/10975271.html