Java -- 线程

来源:互联网 发布:你的理想是什么 知乎 编辑:程序博客网 时间:2024/05/20 19:30

方式一:实现

/*

 * 有两个储户分别向同一个账户存3000元,每次存1000,存3次。每次存完打印账户余额
 * 
 * 1.是否涉及到多线程? 是,因为有两个储户(两种方式创建多线程)
 * 2.是否有共享数据? 是,同一个账户
 * 3.得考虑线程的同步(两种方法处理线程的安全)
 * 
 */




public class Test_Account2 {


public static void main(String[] args) {

Account1 acct = new Account1();
Customer1 c1 = new Customer1(acct);
Customer1 c2 = new Customer1(acct);

Thread t1 = new Thread(c1);
Thread t2 = new Thread(c2);

t1.setName("老哥");
t2.setName("老妹");

t1.start();
t2.start();
}


}


//账户
class Account1{
double balance; //余额

public Account1(){
super();
}
//存钱
public synchronized void deposit(double amt){
balance += amt;

try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":" + balance);
}

}




class Customer1 implements Runnable{
Account1 account1; //每个储户都有一个账户


public Customer1(Account1 account1) {
super();
this.account1 = account1;
}

public void run(){
for (int i = 0; i < 3; i++) {
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
account1.deposit(1000);
}
}

}





方式二:继承

public class Test_Account1 {

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(){
super();
}
//存钱
public synchronized void deposit(double amt){
balance += amt;

try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":" + balance);
}

}




class Customer extends Thread{
Account account; //每个储户都有一个账户


public Customer(Account account) {
super();
this.account = account;
}

public void run(){
for (int i = 0; i < 3; i++) {
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
account.deposit(1000);
}
}

}

原创粉丝点击