就是要求对存款和取款进行同步,如果分别给两个函数加上synchronized,这样在运行时算是实现了不能同时进行存款取款操作,还是不能同时进行两个存款或者取款操作...这样分别加上synchronized,里面的account算是共享变量吗,是否算是在不同线程间加锁?public synchronized void deposit(double a){
account += a;
}
public synchronized  void withdraw(double a ){
account -= a;
}如果是这样呢?
public synchronized void deposit(Boolean k, double a){
if(k==false)
{
this.setKey(true);
account += a;

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

this.setKey(false);
}
else
{System.out.println(this.getId()+"存款等待key");}
}
public synchronized  void withdraw(Boolean k, double a ){
if(k==false)
{
this.setKey(true);
account -= a;

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

this.setKey(false);
}
else
{System.out.println(this.getId()+"取款等待key");}
}谢谢

解决方案 »

  1.   

    建议楼主把代码全部贴出来。1、多线程
    2、共享变量
    3、对于共享变量进行增删操作
    以上三种符合的时候需要synchronize
    对于共享变量
    多个线程共享同一个对象的变量。比如我这有个:public static void main(String[] args) {
    final String r1 = "resource1";
    final String r2 = "resource2";

    Thread t1 = new Thread(){
    @Override
    public void run() {
    synchronized (r1) {
    System.out.println("是"+Thread.currentThread().getName()+"拿到了"+r1);
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }

    synchronized (r2) {

    }
    }
    }
    };

    Thread t2 = new Thread(){
    @Override
    public void run() {
    synchronized (r2) {
    System.out.println("是"+Thread.currentThread().getName()+"拿到了"+r2);
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }

    synchronized (r1) {

    }
    }
    }
    };

    t1.start();
    t2.start();
    }
    这时候是两个线程共享了一个变量。
    这时候是死锁。
    不知道对楼主有没有帮助。