java同步線程(二)
同步方法
同步方法:
使用synchronized關(guān)鍵字來(lái)修飾某個(gè)方法溉躲,則該方法稱為同步方法寸认。
同步方法的同步監(jiān)視器是this,也就是該對(duì)象本身偏塞。
通過(guò)同步方法可以非常方便地實(shí)現(xiàn)線程安全的類,線程安全的類具有如下特征神汹。
1古今、該類的對(duì)象可以被多個(gè)線程安全地訪問(wèn)。
2捉腥、每個(gè)線程調(diào)用該對(duì)象的任意方法之后都將得到正確結(jié)果。
3桃漾、每個(gè)線程調(diào)用該對(duì)象的任意方法之后拟逮,該對(duì)象狀態(tài)依然保持合理的狀態(tài)。
實(shí)現(xiàn)方式如下:
package com.zmy.bank;
public class Account {
//封裝賬戶編號(hào)敦迄,賬戶余額兩個(gè)Eield
private String accountNo;
private double balance;
public Account(String accountNo,double balance)
{
this.accountNo=accountNo;
this.balance=balance;
}
//創(chuàng)建的getter和setter方法
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()+"取錢成功!吐出鈔票"+drawAmount);
try{
Thread.sleep(1);
}catch (InterruptedException e)
{
e.printStackTrace();
}
balance-=drawAmount;
System.out.println("\t余額為:"+balance);
}
else {
System.out.println(Thread.currentThread().getName()+"取錢失敗苦囱!余額不足!");
}
}
@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;
}
//當(dāng)多個(gè)線程修改同一個(gè)共享數(shù)據(jù)時(shí),將涉及數(shù)據(jù)安全性問(wèn)題
@Override
public void run() {
if (account.getBalance() >= drawAmount) {
//突出鈔票
account.draw(drawAmount);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
System.out.println(getName() + "取錢失斝嗯椤喉刘!余額不足!");
}
}
}
package com.zmy.bank;
public class DrawTest {
public static void main(String[] args) {
//創(chuàng)建一個(gè)賬戶
Account acct=new Account("123456",1000);
//simulation two thread draw money from one account
new DrawThread("甲",acct,800).start();
new DrawThread("乙",acct,800).start();
}
}
synchronized 不能修飾構(gòu)造器睦裳、屬性