需求:储户,两个,每个都到银行存钱,每次存100,共存三次。- class Bank{
- private int sum ;
- public void add(int num){
- synchronized(this ){
- sum = sum + num;
- 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);
- }
- }
- }
- class BankDemo{
- public static void main(String[] args){
- Cus c = new Cus();
- Thread t1 = new Thread(c);
- Thread t2 = new Thread(c);
- t1.start();
- t2.start();
- }
- }
复制代码 主函数里面的只创建了1个储户对象,不是说2个储户吗?即使是多线程也得是2个储户的吧?
但是写这个不对,求解
new Thread(new Cus()).start();
new Thread(new Cus()).start();
|
|