我是否可以创建一个包含字符串的对象树。例如,如下所示
T1
|
T2
/\
T3 T4
\ /
T5
创建此类树的语法是什么?我试图让它们按顺序,并行和嵌套顺序运行。
这是我到目前为止所写的内容:
public class Tasks {
public Node node;
public String put(String value, int[] path){
Node current = node;
for(int i=0;i<path.length;i++){
if(current.children.get(i)==null){
current.children.add(i, new Node());
}
current = current.children.get(i);
}
String ret = current.value;
current.value = value;
Tasks myTask = new Tasks();
myTask.node = new Node();
int[] path1 = {0, 0, 0};
myTask.put("T1", path1);
System.out.println(myTask.get(path1));
}
}
public class Node{
public ArrayList<Node> children;
public Node parent;
public String value;
}
答案 0 :(得分:1)
请使用根据您给定的树结构组织的ExecutorService和Callable任务来查看此示例。它已准备好运行,因此您可以对其进行测试并进行实验:
public class Test {
public static void main(String[] args) throws Exception {
// Declare a new ExecutorService with a maximum of 2 threads.
ExecutorService service = Executors.newFixedThreadPool(2);
// Declare the tasks.
StringTask t1 = new StringTask("First task!");
StringTask t2 = new StringTask("Second task!");
StringTask t3 = new StringTask("Third task!");
StringTask t4 = new StringTask("Fourth task!");
StringTask t5 = new StringTask("Fifth task!");
// Submit the first task.
String result1 = service.submit(t1).get(); // Using the .get() directly blocks the waiting for completion of the task.
System.out.println("T1 result: " + result1);
// Submit the second task.
String result2 = service.submit(t2).get();
System.out.println("T2 result: " + result2);
// Prepare the list of parallel tasks and invoke them.
List<StringTask> parallelTasks = new ArrayList<>(2);
parallelTasks.add(t3);
parallelTasks.add(t4);
List<Future<String>> results = service.invokeAll(parallelTasks); // Note that using .invokeAll() will block the
// execution until all tasks are completed.
for (Future<String> result : results) {
System.out.println("Parallel task result: " + result.get());
}
// Submit the last task.
String result5 = service.submit(t5).get();
System.out.println("T5 result: " + result5);
}
/**
* Callable task that reverses a given String.
*/
private static final class StringTask implements Callable<String> {
private String input;
private StringTask(String input) {
super();
if (input == null) {
throw new NullPointerException();
}
this.input = input;
}
@Override
public String call() throws Exception {
StringBuilder builder = new StringBuilder();
for (int i = this.input.length() - 1; i >= 0; i--) {
builder.append(this.input.charAt(i));
}
return builder.toString();
}
}
}
如果事先知道任务及其组织方式,您可以用类似的方式硬编码。但是,如果任务结构不是静态的或事先不知道,您可能希望实现自己的任务树结构(例如,使用CallableNode
个对象)并使用ExecutorService
来完成该树和根据其结构执行任务。