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);
}
}
}
![](https://profile-avatar.csdnimg.cn/ce73733312c54450bd862916c1693422_weixin_45711143.jpg!4)
创建线程遇到一些小问题
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- stacksoverflow 2021-09-06 10:22关注
第4行改成
Customer c1 = new Customer(new Account(100));本回答被专家选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 三分类机器学习模型可视化分析
- ¥15 本地测试网站127.0.0.1 已拒绝连接,如何解决?(标签-ubuntu)
- ¥50 Qt在release捕获异常并跟踪堆栈(有Demo,跑一下环境再回答)
- ¥30 python,LLM 文本提炼
- ¥15 关于将inet引入的相关问题
- ¥15 关于一个倒计时的操作和显示设计
- ¥15 提问STK的问题,哪位航天领域的同学会啊
- ¥15 苹果系统的mac m1芯片的笔记本使用ce修改器使用不了
- ¥15 单相逆变的电压电流双闭环中进行低通滤波PID算法改进
- ¥15 关于#java#的问题,请各位专家解答!