對於同步,在具體的Java代碼中需要完成以下兩個操作:
把競爭訪問的資源標識爲private;
同步那些修改變量的代碼,使用synchronized關鍵字同步方法火代碼。
synchronized關鍵字智能標記費抽象方法,不能標記成員變量
爲了演示同步方法的使用,構建了一個信用卡賬戶,起初信用額爲100w,然後模擬透支、存款等多個操作。顯然銀行賬戶User對象是個競爭資源,而多個併發操作的是賬戶方法oper(int x),當然應該在此方法上加上同步,並將賬戶的餘額設爲私有變量,禁止直接訪問。
以下是代碼:
public class Test {
public static void main(String args[]){
User u=new User("張三",100);
MyThread t1=new MyThread("線程A",u,20);
MyThread t2=new MyThread("線程B",u,20);
MyThread t3=new MyThread("線程C",u,20);
MyThread t4=new MyThread("線程D",u,20);
MyThread t5=new MyThread("線程E",u,20);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
static class MyThread extends Thread{
private User u;
private int y=0;
MyThread (String name,User u,int y){
super(name);
this.u=u;
this.y=y;
}
public void run(){
u.oper(y);
}
}
static class User{
private String code;
private int cash;
User (String code,int cash){
this.code=code;
this.cash=cash;
}
public String getCode(){
return code;
}
public void setCode(String code){
this.code=code;
}
public synchronized void oper(int x){
try{
Thread.sleep(10L);
this.cash+=x;
System.out.println(Thread.currentThread().getName()+"運行結束,增加“"
+x+"“,當前賬戶餘額爲:"+cash);
}catch(InterruptedException e){
e.printStackTrace();
}
}
public String toString(){
return "User{"+"code="+code+",cash="+cash+"}";
}
}
}
關鍵點就在於
public synchronized void oper(int x){
同步了這個方法,只允許一個線程進行訪問,因而避免錯誤的出現
代碼已經驗證過了,能夠實現功能