gpt4 book ai didi

java - 对 ArrayList 起作用的两种方法的同步

转载 作者:行者123 更新时间:2023-12-03 12:44:27 26 4
gpt4 key购买 nike

我有 总和 类(class), 创作者 类(class), 项目 类(class)和主页 . 创作者 创建随机项并将它们添加到 中的 ArrayList项目 类(class)。 总和 类读取项目并总结所有项目的重量。在 主页 我在多个线程中开始的类创作者 总和 .两个类都实现了 可运行 并覆盖 run 方法。在控制台中打印 200 个创建后的项目。
如何同步这些方法? 当我启动线程时,Sum 中的方法首先结束并返回权重 0,然后创建者创建 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");
}

最佳答案

BlockingQueue我建议使用 BlockingQueue 的实现接口(interface),而不是 ArrayList .一个 BlockingQueuethread-safe .
引用 Javadoc:

BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control. However, the bulk Collection operations addAll, containsAll, retainAll and removeAll are not necessarily performed atomically unless specified otherwise in an implementation. So it is possible, for example, for addAll(c) to fail (throwing an exception) after adding only some of the elements in c.


示例代码
 class Producer implements Runnable {
private final BlockingQueue queue;
Producer(BlockingQueue q) { queue = q; }
public void run() {
reader=new Scanner(text);
while(reader.hasNextLine()){
counter++;
String[] x=reader.nextLine().split("_");
q.put(new Towar(x[0], Integer.parseInt(x[1])));
if(counter%200==0){
System.out.println("Created "+counter+" items");
}
}
q.put(null);
System.out.println("Created in total: "+counter+" items");
}
}

class Consumer implements Runnable {
private final BlockingQueue queue;
Consumer(BlockingQueue q) { queue = q; }
public void run() {
long sum = 0;
try {
while (true) {
Towar x = (Towar)queue.take();
if (x == null) return;
counter++;
sum+=x.getWaga();
if(counter%100==0){
System.out.println("Sum of "+counter+" items");
}
}
} catch (InterruptedException ex) { ... handle ...}
}
}

关于java - 对 ArrayList 起作用的两种方法的同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65727588/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com