package thread;
public class ThreadTest1 {
public static void main(String[] args) {
//創建一個公用的賬戶
Account act = new Account("zhangsan",5000.0);
Thread t1 = new Thread(new PrimeRun(act));
Thread t2 = new Thread(new PrimeRun(act));
//設置線程的名字
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
}
//創建取款線程
class PrimeRun implements Runnable{
Account act ;
PrimeRun(Account act){
this.act = act;
}
public void run() {
try {
act.withDraw(1000.0);
System.out.println(Thread.currentThread().getName()+ "取款1000.0成功,所剩餘額:" + act.getBalance());
} catch (Exception e) {
e.printStackTrace();
}
}
}
//賬戶
class Account{
private String actno;
private double balance;
Account(){};
//給賬戶賦初始值
Account(String actno,double balance){
this.actno = actno;
this.balance = balance;
}
//取款餘額
public void withDraw(double money){
double after = balance - money;
try {
Thread.sleep(2000); //爲達到預期效果,此處線程休眠2秒
} catch (Exception e) {
e.printStackTrace();
}
this.balance = after;
}
public String getActno() {
return actno;
}
public void setActno(String actno) {
this.actno = actno;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
}
我們看看輸出結果:
t2取款1000.0成功,所剩餘額:4000.0
t1取款1000.0成功,所剩餘額:4000.0
結果很明顯不符合要求:代碼重新修改如下:
package thread;
public class ThreadTest1 {
public static void main(String[] args) {
//創建一個公用的賬戶
Account act = new Account("zhangsan",5000.0);
Thread t1 = new Thread(new PrimeRun(act));
Thread t2 = new Thread(new PrimeRun(act));
//設置線程的名字
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
}
//創建取款線程
class PrimeRun implements Runnable{
Account act ;
PrimeRun(Account act){
this.act = act;
}
public void run() {
try {
act.withDraw(1000.0);
System.out.println(Thread.currentThread().getName()+ "取款1000.0成功,所剩餘額:" + act.getBalance());
} catch (Exception e) {
e.printStackTrace();
}
}
}
//賬戶
class Account{
private String actno;
private double balance;
Account(){};
//給賬戶賦初始值
Account(String actno,double balance){
this.actno = actno;
this.balance = balance;
}
//取款餘額
public void withDraw(double money){
synchronized (this) {
double after = balance - money;
try {
Thread.sleep(2000); //爲達到預期效果,此處線程休眠2秒
} catch (Exception e) {
e.printStackTrace();
}
this.balance = after;
}
}
public String getActno() {
return actno;
}
public void setActno(String actno) {
this.actno = actno;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
}
再看輸出結果:
t1取款1000.0成功,所剩餘額:4000.0
t2取款1000.0成功,所剩餘額:3000.0
通過上述例子:
t1和t2兩線程,如果當t1遇到synchronized關鍵字,就會找this的對象鎖,如果找到this對象鎖,則進入同步語句塊,當該同步語句中代碼執行結束後,t1線程歸還this對象鎖。