用Java优化多线程队列处理代码

时间:2015-06-16 19:59:37

标签: java multithreading queue runnable volatile

我有一个代码,可以创建一个类的10个对象,实现runnable。 每个对象都保存在hashmap中以供以后使用。 每个对象都在一个单独的线程上运行。每个对象都有一个公共方法,可以将项添加到队列中。 该对象使用无限循环处理队列。

我想知道这个解决方案是否正常,或者是否存在完全错误/无用/丢失的问题(特别是使用volatile和同步关键字)?

MultithreadingTest.class

package multithreadingtest;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Multithreading example.
 *
 * @author lkallas
 */
public class MultithreadingTest {

    private static final int NUM_OF_THREADS = 10;
    private static String name;
    private static final Map<Integer, ThreadWorker> objectMap = new HashMap<>();    //Map or storing Threadworker objects

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(NUM_OF_THREADS);
        //Creating threads
        for (int i = 0; i < NUM_OF_THREADS; i++) {
            name = "ThreadWorker" + String.valueOf(i);
            ThreadWorker thread = new ThreadWorker(name);
            objectMap.put(i, thread);   //Add objects to map            
            executor.execute(thread);
        }
        for (int i = 0; i < 10; i++) {
            ThreadWorker worker = objectMap.get(i);
            for (int j = 0; j < 10; j++) {
                worker.addToQueue("Test1");
            }
        }
    }
}

ThreadWorker.class

package multithreadingtest;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Worker class that performs operations in another thread.
 *
 * @author lkallas
 */
public class ThreadWorker implements Runnable {

    private final String threadName;
    private volatile Queue workQueue;   //Does this have to volatile??

    /**
     * Class constructor.
     *
     * @param threadName Name of the thread for identifying.
     *
     */
    public ThreadWorker(String threadName) {
        this.threadName = threadName;
        this.workQueue = new LinkedList();
        System.out.println(String.format("Thread %s started!", threadName));
    }

    /**
     * Adds items to the queue.
     *
     * @param object Object to be added to the queue.
     */
    public synchronized void addToQueue(String object) {
        workQueue.add(object); //Does it have to be syncronized void
    }

    @Override
    public void run() {
        while (true) {
            if (!workQueue.isEmpty()) {
                System.out.println("Queue size: " + workQueue.size());
                String item = (String) workQueue.peek();
                //Process item
                System.out.println(threadName + " just processed " + item);
                workQueue.remove();
            }
        }
    }
}

非常感谢任何帮助和建议!

1 个答案:

答案 0 :(得分:2)

  1. workQueue是线程本地的,不需要是volatile(它是私有的,没有公共的setter方法)
  2. 使workQueue成为BlockingQueue - 此队列是线程安全的,因此您无需同步addToQueue。此外,您不需要在run内部旋转 - 而是在队列上调用take(),并且线程会阻塞直到项目可用。
  3. 您似乎在MultithreadingTest内部做了太多工作 - 而不是将项目添加到各个队列,您可以让所有工作人员共享相同的BlockingQueue,然后main只需要将项目添加到单个BlockingQueue,工作人员将负责自己的负载平衡。请注意,即使共享BlockingQueue,它仍然不需要volatile,因为一旦初始化了一个worker,对BlockingQueue的引用就不会改变(make the field { {1}} - private final BlockingQueue<String> workQueue字段永远不需要final)。