gpt4 book ai didi

java - 通过多线程提高性能

转载 作者:太空宇宙 更新时间:2023-11-04 14:42:32 24 4
gpt4 key购买 nike

我正在编写一个Java程序来解决这个问题:

我有一个包含值的平衡树(即Java中的TreeSet)。我有“任务”对象,可以执行以下两件事之一:尝试在树中查找值,或向树添加值。我将拥有这些“任务”对象的列表(我在 Java 中使用了 LinkedList),并且创建线程来从该列表中一一读取和删除任务,并执行其所需的操作(即,在树)。我为我的任务列表创建了一个同步的“删除”方法(它只是调用底层 LinkedList 的“删除”方法)。我还定义了要同步的树的“add”方法...(我不知道是否有必要同步,但我认为有必要)。

使用多线程时如何提高该程序的性能?现在,如果我使用单线程,时间比使用多线程时要好。

这是run我的方法TaskRunner类,我的线程是该类的对象,它实现 Runnable , tasks是包含任务和 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);
}

此外,我的树继承自 TreeSet<Integer>在Java中,我定义了它的add方法为synchronized :

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

我的任务列表继承自 LinkedList<Task>及其 remove方法:

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

最佳答案

如果你的任务类实现了Runnable接口(interface),你可以使用ThreadPool来处理任务。这是一个例子:

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();
}

}

关于java - 通过多线程提高性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24786496/

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