public class CustomerTest {
public static void main(String[] args) {
Customer c1 = new Customer();
Thread t1 = new Thread(c1);
Thread t2 = new Thread(c1);
t1.setName("线程一:");
t2.setName("线程二:");
t1.start();
t2.start();
}
}
class Account{
private double balance;
public Account(double balance){
this.balance = balance;
}
public synchronized void deposit(double amt){
if(amt > 0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
balance += amt;
}
System.out.println(Thread.currentThread().getName() + ": 存钱成功,余额为:" + balance);
}
}
class Customer implements Runnable{
private Account account;
public Customer(){};
public Customer(Account account){
this.account = account;
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
account.deposit(1000);
}
}
}public class CustomerTest {
public static void main(String[] args) {
** Customer c1 = new Customer();****我这里调用空参构造器,运行时为什么会出现空指针__**。
Thread t1 = new Thread(c1);
Thread t2 = new Thread(c1);
t1.setName("线程一:");
t2.setName("线程二:");
t1.start();
t2.start();
}
}
class Account{
private double balance;
public Account(double balance){
this.balance = balance;
}
public synchronized void deposit(double amt){
if(amt > 0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
balance += amt;
}
System.out.println(Thread.currentThread().getName() + ": 存钱成功,余额为:" + balance);
}
}
class Customer implements Runnable{
private Account account;
public Customer(){};
public Customer(Account account){
this.account = account;
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
account.deposit(1000);
}
}
}
第4行改成
Customer c1 = new Customer(new Account(100));
86行,你的account都没set,肯定空指针,null没有deposit方法