java synchronization thread (2)
Synchronization method
Synchronization method:
Using the synchronized keyword to decorate a method is called a synchronized method.
The synchronization monitor of the synchronization method is this, which is the object itself.
It is very convenient to implement thread safe classes through synchronization method. Thread safe classes have the following characteristics.
1. Objects of this class can be accessed safely by multiple threads.
2. Each thread will get the correct result after calling any method of the object.
3. After each thread calls any method of the object, the state of the object remains reasonable.
The implementation method is as follows:
package com.zmy.bank; public class Account { //Package account number, account balance two Eield private String accountNo; private double balance; public Account(String accountNo,double balance) { this.accountNo=accountNo; this.balance=balance; } //getter and setter methods created public String getAccountNo() { return accountNo; } public void setAccountNo(String accountNo) { this.accountNo = accountNo; } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } public synchronized void draw(double drawAmount) { if(balance>=drawAmount) { System.out.println(Thread.currentThread().getName()+"Successful withdrawals!Spit out banknotes"+drawAmount); try{ Thread.sleep(1); }catch (InterruptedException e) { e.printStackTrace(); } balance-=drawAmount; System.out.println("\t The balance is:"+balance); } else { System.out.println(Thread.currentThread().getName()+"Failed to withdraw money! Sorry, your credit is running low!"); } } @Override public int hashCode() { return accountNo.hashCode(); } @Override public boolean equals(Object obj) { if (this==obj) return true; if (obj !=null&&obj.getClass()==Account.class) { Account target=(Account)obj; return target.getAccountNo().equals(accountNo); } return false; } }
package com.zmy.bank; public class DrawThread extends Thread { private Account account; private double drawAmount; public DrawThread(String name, Account account, double drawAmount) { super(name); this.account = account; this.drawAmount = drawAmount; } //When multiple threads modify the same shared data, data security issues will be involved @Override public void run() { if (account.getBalance() >= drawAmount) { //Outstanding banknote account.draw(drawAmount); try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } else { System.out.println(getName() + "Failed to withdraw money! Sorry, your credit is running low!"); } } }
package com.zmy.bank; public class DrawTest { public static void main(String[] args) { //Create an account Account acct=new Account("123456",1000); //simulation two thread draw money from one account new DrawThread("nail",acct,800).start(); new DrawThread("B",acct,800).start(); } }
synchronized cannot modify constructor or attribute