一个关于多线程的问题?请高手们帮帮我
跑路的蛤蟆 2008-04-16 05:51:26
public class ThreadRunnable{
public static void main(String[] args){
Person.t1.start();
Person.t2.start();
}
}
class Person implements Runnable{
public int i;
static Thread t1 = new Thread(new Person(1));
static Thread t2 = new Thread(new Person(2));
public Person(int i){
this.i = i;
}
ATM atm = new ATM();
public void run() {
synchronized(atm){
if(i==1){
try {
ATM.withDraw(20,i);
atm.wait();
ATM.dispose(20, i);
atm.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
try {
ATM.withDraw(20, i);
atm.notify();
atm.wait();
ATM.dispose(20, i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class ATM{
static double total=1000;
public static void dispose(double x,int i){
total = total +x;
System.out.println("person"+i+" dispose");
System.out.println(ATM.getTotals());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void withDraw(double x,int i){
total = total -x;
System.out.println("person"+i+" withDraw");
System.out.println("the rest of money"+ATM.getTotals());
try {
Thread.sleep(8000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static double getTotals(){
return total;
}
}
这是程序,我想让它的结果是:
person1 withDraw
the rest money 980
person2 withDraw
the rest money 960
person1 dispose
the rest money 980
person2 dispose
the rest money 1000
但是它现在有问题.不是期望的结果.5555555555请大家帮帮我.