Java学习日记-----多线程-----作业

①继承方式(extends Thread)

package testSingleton;

public class TestAccount {

    public static void main(String[] args) {
        Account acct = new Account();
        Customer c1 = new Customer(acct);
        Customer c2 = new Customer(acct);
        
        c1.setName("甲");
        c2.setName("乙");
        
        c1.start();
        c2.start();

    }

}
class Account{
    double balance; //余额
    public Account() {
        
    }
    //存钱
    public synchronized void deposit(double amt) {
        balance += amt;
        try {
            Thread.currentThread().sleep(10);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + ":" + balance);
    }
    
}
class Customer extends Thread{
    Account account;
    public Customer(Account account) {
        this.account = account;
    }
    public void run() {
        for(int i =0;i<3;i++) {
            account.deposit(1000);
        }
    }
}

②实现方式(implements Runnable)

package testSingleton;

public class TestAccount2 {
    
    public static void main(String[] args) {
        Account1 accc = new Account1();
        Customer1 c1 = new Customer1(accc);
        Customer1 c2 = new Customer1(accc);
        
        Thread t1 = new Thread(c1);
        Thread t2 = new Thread(c2);
        
        t1.setName("郭浩");
        t2.setName("风窗");
        
        t1.start();
        t2.start();
        
        
    }
}
class Account1{
    double balance;
    public Account1(){
        
    }
    //存钱
    public synchronized void depsoit(double e){
        balance+=e;
        System.out.println(Thread.currentThread().getName()+":"+balance);
    }
}
class Customer1 implements Runnable{
    Account1 account;
    public Customer1(Account1 acc) {
        this.account = acc;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        for(int i=0;i<3;i++) {
            account.depsoit(1000);
            
        }
    }
    
}

猜你喜欢

转载自www.cnblogs.com/Gaohy/p/8948152.html
今日推荐