通过多线程模拟取款,讲解 synchronized

1450阅读 0评论2014-03-18 xu2428847702
分类:Java

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对象锁。
上一篇:sql的使用详解(针对oeacle)之select(上)
下一篇:双缓存绘图浅谈