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

标签 java multithreading arraylist synchronization runnable

我有 总和 类(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/

相关文章:

java - 当 Node 泛型与 List 泛型不同时,在 Java 泛型列表中实现 Iterable

c# - 线程启动<线程池> : When i get data from api

android - 如何将对象列表写入 firebase?

c++ - C++中是否有可等待的队列?

java - 如果发生异常则停止ThreadPool中的所有线程

groovy - 加入 bool 元素列表groovy

Java:我应该总是用 ArrayLists 替换 Arrays 吗?

java - java.util.Map 属性的 Jaxb 命名空间

java - 在 strings.xml 中本地化字符串会产生 NullPointerException

java - 在java中 `.properties`文件在编辑模式下没有显示任何内容