学写多线程,在3个类里对象不知道怎么传递。

SilentHunter460 2020-09-10 11:43:34
以下问题,如果用内部类的方式可以解决,但分在三个独立类里,对象参数不知道怎么传递。

这是一个要操作的类,每次运行deposit方法就为amount变量加1,用synchronized做同步。

public class Account {
int amount;

Account() {
}

public synchronized void deposit() {
amount += 1;
}
}


这个类搞线程池,Account类的实例化对象放在这里。

public class AccountWithSync {
Account myaccount = new Account();
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
executor.execute(new addOnePenny());
}
}
}


实现Runnable接口的类,以便主类可以用线程池。必须在这个类里完成调用Account类的deposit方法,可是它的实例化对象myaccount却在AccountWithSync那个类里面。

class addOnePenny implements Runnable{
@Override
public void run() {

}
}
...全文
3942 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
qybao 2020-09-11
  • 打赏
  • 举报
回复
在 addOnePenny 类里加个Account 类型的成员变量,然后加个addOnePenny(Account a)构造方法把Account对象赋给addOnePenny的成员变量,这样在addOnePenny的方法里就可以操作Account成员变量了。 main方法里 executor.execute(new addOnePenny(myaccount)); 即可,所有线程就会共享这个myaccount
一个帅逼 2020-09-11
  • 打赏
  • 举报
回复

public class AccountWithSync {
      static Account myaccount = new Account();
      public static void main(String[] args) {
             ExecutorService executor = Executors.newCachedThreadPool();
             for (int i = 0; i < 10; i++) {
                   executor.execute(new addOnePenny(myaccount ));
             }
      }
}

class addOnePenny implements Runnable{
      private Account account;
       public addOnePenny(Account account){
          this.account = account;
       }

      @Override
      public void run() {
          account.deposit();
      }
}

62,634

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧