由银行账户的存取款线程设计提出
class Account{
volatile private int value;
void put(int i){
value+=i;
System.out.println("存入"+i+"线上金额为:"+value);
}
int get(int i){
if(value>i){
value-=i;
}
else{
i=value;
value=0;
}
System.out.println("取走"+i+"线上金额为:"+value);
}
}
class Save implements Runnable{
private Account a1;
public Save(Account a1){
this.a1=a1;
}
public void run(){
while(true){
a1.put(100);
}
}
}
class Fetch implements Runnable{
private Account a1;
public Fetch(Account a1){
this.a1=a1;
}
public void run(){
while(true){
a1.get(100);
}
}
}
public class TestCommunicate {
public static void main(String []args){
Account a1=new Account();
new Thread(new Save(a1)).start();
new Thread(new Fetch(a1)).start();
}
}
输出结果可能是:
存入100线上金额为:13254000
存入100线上金额为:13254100
存入100线上金额为:13254200
存入100线上金额为:13254300
存入100线上金额为:13254400
存入100线上金额为:13254500
程序结果和原设想存在差距 加入synchronized监视器后只能保证同一时刻只能有一个线程存或取
将Account类如下改动
class Account{
volatile private int value;
volatile private boolean isMoney=false;
synchronized void put(int i){
if(isMoney){
try{
wait();
}
catch(Exception e){}
}
value+=i;
System.out.println("存入"+i+"线上金额为:"+value);
isMoney=true;
notify();
}
synchronized int get(int i){
if(!isMoney){
try{
wait();
}
catch(Exception e){}
}
if(value>i){
value-=i;
}
else{
i=value;
value=0;
}
System.out.println("取走"+i+"线上金额为:"+value);
isMoney=false;
return i;
}
}
class Save implements Runnable{
private Account a1;
public Save(Account a1){
this.a1=a1;
}
public void run(){
while(true){
a1.put(100);
}
}
}
class Fetch implements Runnable{
private Account a1;
public Fetch(Account a1){
this.a1=a1;
}
public void run(){
while(true){
a1.get(100);
}
}
}
public class TestCommunicate {
public static void main(String []args){
Account a1=new Account();
new Thread(new Save(a1)).start();
new Thread(new Fetch(a1)).start();
}
}
输出结果是:
存入100线上金额为:100
取走100线上金额为:0
利用wait()方法、notify()方法交叉唤醒线程来达到程序目的