黑马程序员技术交流社区
标题:
请教,线程同步问题
[打印本页]
作者:
rxtm
时间:
2015-7-22 20:34
标题:
请教,线程同步问题
Java code
import java.io.*;
class Account
{
private String name;
private double balance;
public Account(String name)
{
this.name=name;
balance=0;
}
public String getName()
{
return name;
}
public double getBalance()
{
return balance;
}
public void put(double value)
{
if(value>0)
balance=balance+value;
}
public double get(double value)
{
if(value>0)
{
if(value<=this.balance)
this.balance-=value;
else
{
value=this.balance;
this.balance=0;
}
return value;
}
else
return 0;
}
}
class Save extends Thread
{
private double val;
private Account account;
public Save(Account a1,double val)
{
this.account=a1;
this.val=val;
}
public void run()
{
double howmuch;
howmuch=this.account.getBalance();
this.account.put(val);
try
{
sleep(1);
}
catch(InterruptedException e) { }
System.out.println(this.account.getName()+"账户:现有"+howmuch+",存入:"+this.val+",余额:"+this.account.getBalance());
}
}
class Fetch extends Thread
{
private double val;
private Account account;
public Fetch(Account a1,double val)
{
this.account=a1;
this.val=val;
}
public void run()
{
double howmuch=this.account.getBalance();
try
{
sleep(1);
}
catch(InterruptedException e){}
System.out.println(this.account.getName()+"账户:现有"+howmuch+",取出:"+this.account.get(val)+",余额:"+this.account.getBalance());
}
}
public class App2_1 {
public static void main(String args[])
{
Account wang=new Account("wang");
(new Save(wang,100)).start();
(new Save(wang,200)).start();
(new Fetch(wang,300)).start();
}
}
有一次运行结果如下:
wang账户:现有300.0,取出:300.0,余额:0.0
wang账户:现有0.0,存入:100.0,余额:0.0
wang账户:现有100.0,存入:200.0,余额:300.0
怎么想也想不出这3个线程是按什么顺序推进的,尤其是最后一行的余额为什么是300,不应该是0吗?
更多 0
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2