java---Thread(Account)

来源:互联网 发布:淘宝上好看的卫衣店 编辑:程序博客网 时间:2024/06/05 19:28
/*
 * 有两个储户分别向同一个账户存3000元,每次存1000,存 3次。每次存完打印账户余额
 * 1.是否涉及到多线程?是,因为有两个账户
 * 2.是否有共享数据?有,同一个账户
 * 3.的考虑线程的同步(两种方法处理线程的安全)
 */
public class TestThreadBank {
public static void main(String[] args) {
// Account a = new Account();
// Thread t = new Thread(a);
// Thread t1 = new Thread(a);
// t.start();
// t.setName("储户一");
// t1.start();
// t1.setName("储户二");
Account acct = new Account();
Customer c1 = new Customer(acct);
Customer c2 = new Customer(acct);
Thread t1 = new Thread(c1);
Thread t2 = new Thread(c1);
t1.setName("老公");
t2.setName("老婆");
t1.start();
t2.start();
}

}
//此种方案不规范
//class Account implements Runnable{
// int money = 0;//余额
//
// public Account(int money) {
// super();
// }
//
// @Override
// public void run() {
// int num = 1;
// while(true){
// synchronized (this) {
// if(money < 6000 && num <= 3){
//   try {
// Thread.currentThread().sleep(100);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// System.out.println(Thread.currentThread().getName() + ":" + "账户余额:" + 
// (money = money + 1000) + "已存次数:" + num++);
// }else{
// break;
// }
// }
// }
// }
//}
class Account{
double balance;//余额


public Account() {
super();
// TODO Auto-generated constructor stub
}

//存钱
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) {
// super();
// this.account = account;
// }
// public void run(){
// for(int i = 0; i < 3; i++){
// try {
// Thread.currentThread().sleep(10);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// account.deposit(1000);
// }
// }
//}
//储户//实现方式的
class Customer implements Runnable{
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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
account.deposit(1000);
}
}
}
原创粉丝点击