简体   繁体   English

使用多线程提高性能

[英]Improve Performance with Multiple Threads

I'm writing a Java program to solve this problem: 我正在编写一个Java程序来解决此问题:

I have a balanced tree (namely, a TreeSet in Java) containing values. 我有一棵包含值的平衡树(即Java中的TreeSet)。 I have "Task" objects that will do either of the two things: try to find a value in the tree, or add a value to the tree. 我有“任务”对象,将执行以下两项操作之一:尝试在树中查找值,或向树中添加值。 I will have a list of these "Task" objects (I used a LinkedList in Java) and I create threads to read and remove the tasks from this list one by one and perform their required action (ie, find or add a value in the tree). 我将获得这些“任务”对象的列表(我在Java中使用了LinkedList),并创建线程以逐个读取和删除此列表中的任务,并执行其所需的操作(即,在树)。 I have created a synchronized "remove" method for my task list (which simply calls the underlying LinkedList's "remove" method). 我为任务列表创建了一个同步的“删除”方法(该方法简单地调用了底层LinkedList的“删除”方法)。 I have also defined the "add" method of the tree to be synchronized... (I don't know if it's necessary for it to be synchronized or not, but I assume it is). 我还定义了要同步的树的“添加”方法...(我不知道是否需要同步它,但我认为是必须的)。

How can I improve the performance of this program when using multiple threads? 使用多个线程时,如何提高该程序的性能? Right now, if I use a single thread, the time is better than when I use multiple threads. 现在,如果我使用一个线程,则时间要比使用多个线程的时间要好。

This is the run method of my TaskRunner class, my threads are objects of this class and it implements Runnable , tasks is the list containing tasks and tree is my TreeSet passed to this object in the constructor: 这是TaskRunner类的run方法,我的线程是此类的对象,它实现Runnabletasks是包含任务的列表, tree是我的TreeSet传递给构造函数中的该对象:

Task task;
int action;     // '0' for search, '1' for add
int value;      // Value to be used for searching or adding

while (!tasks.isEmpty()) {
    try { task = tasks.remove(); }
    catch (NoSuchElementException ex) { break; }

    action = task.getAction();
    value = task.getValue();

    if (action == 0)
        boolean found = tree.contains(value);
    else
        tree.add(value);
}

Also, my tree inherits from TreeSet<Integer> in Java and I have defined its add method as synchronized : 另外,我的树继承自Java中的TreeSet<Integer> ,并且已将其add方法定义为synchronized

public synchronized boolean add(Integer e) {
    return super.add(e);
}

And my task list inherits from LinkedList<Task> and its remove method: 我的任务列表继承自LinkedList<Task>及其remove方法:

public synchronized Task remove() {
    return super.remove();
}

If your task class implements Runnable interface, you can use ThreadPool to process the tasks. 如果您的任务类实现了Runnable接口,则可以使用ThreadPool处理任务。 Here is an example: 这是一个例子:

public class TreeSetTaskExample {

public static class Task implements Runnable {

    String      value;
    boolean     add;
    Set<String> synchronizedTreeSet;

    public Task(String value, boolean add, Set<String> synchronizedTreeSet) {
        this.value = value;
        this.add = add;
        this.synchronizedTreeSet = synchronizedTreeSet;
    }

    @Override
    public void run() {

        String threadName = Thread.currentThread().toString();

        if (add) {
            System.out.println(threadName + "# add: " + value);
            synchronizedTreeSet.add(value);
        } else {
            boolean contains = synchronizedTreeSet.contains(value);

            System.out.println(threadName + "# treeSet.contains: " + value + " = " + contains + " removed...");

            if (contains) {
                synchronizedTreeSet.remove(value);
            }
        }

    }
}

public static void main(String[] args) throws InterruptedException {

    //
    // synchronizedSet
    //
    Set<String> treeSet = Collections.synchronizedSet(new TreeSet<String>());

    //
    // ThreadPool with ? Threads
    //
    int processors = Runtime.getRuntime().availableProcessors();
    ExecutorService threadPool = Executors.newFixedThreadPool(processors);

    for (int i = 0; i < 100; i++) {

        String someValue = "" + (i % 5);
        boolean addOrCheck = Math.random() > 0.5;

        threadPool.execute(new Task(someValue, addOrCheck, treeSet));
    }

    //
    // don't forget to kill the threadpool
    //
    threadPool.shutdown();
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM