【发布时间】:2021-04-19 23:31:47
【问题描述】:
我有 Sum 类、Creator 类、Item 类和 Main。 Creator 创建随机项并将它们添加到 Item 类中的 ArrayList 中。 Sum 类读取项目并将所有的重量相加。在 Main 类中,我从多个线程 Creator 和 Sum 开始。这两个类都实现了 Runnable 并覆盖了 run 方法。 200 个创建后的项目在控制台中打印。
如何同步这些方法?当我启动线程时,Sum 中的方法首先结束并返回权重 0,然后 Creator 创建 40 000 个随机项目。我将创建项目,同时对它们的所有权重求和,最后返回创建了多少个项目以及所有项目的权重。
求和类方法:
@Override
public synchronized void run() {
for(Towar x: Towar.list){
try {
Thread.currentThread().wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
counter++;
sum+=x.getWaga();
if(counter%100==0){
System.out.println("Sum of "+counter+" items");
}
}
System.out.println("Total weight of Items: "+sum);
}
创建者类方法:
@Override
public void run() {
reader=new Scanner(text);
while(reader.hasNextLine()){
counter++;
String[] x=reader.nextLine().split("_");
synchronized (Towar.getList()){
Towar.add(new Towar(x[0], Integer.parseInt(x[1])));
Towar.list.notify();
if(counter%200==0){
System.out.println("Created "+counter+" items");
}
}
}
System.out.println("Created in total: "+counter+" items");
}
【问题讨论】:
标签: java multithreading arraylist synchronization runnable