//需求:两个储户,去同一个银行,存钱,每人存三次,每次100元。
class Bank {
private int sum;
public synchronized void add(int num) {
sum = sum + num;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("sum=" + sum);
}
}
class Cus implements Runnable {
private Bank b = new Bank();
public void run() {
for (int x = 0; x < 3; x++) {
b.add(100);
}
}
}
public class Test {
public static void main(String[] args) {
Cus c = new Cus();// 不是两个储户去同一个银行存钱嘛,怎么只创建了一个储户对象,而用run方法表示储户存钱呢?ps:新人,问题无限多。
Thread t1 = new Thread(c);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}