int num_threads = 4;
List<List<Integer>> seq;
//created four new magnetization thread
Magnetizationthread myt[] = new Magnetizationthread[num_threads];
//go through the newlycreated thread
for (int i = 0; i < myt.length; ++i) {
//initializes the thread one by one
myt[i] = new Magnetizationthread(i + 1);
myt[i].start();
//store the sequences genarted in a List
seq = myt[i].generateSequences(2);
for (i = 0; i < seq.size(); i++) {
//gets the sequence generated by the threads
System.out.println(seq.get(i) + "configuration " + i);
}
**不知道如何获取单个线程的总和,然后从数组中获取它们的总和
I have generated the threads for each configuration and tried adding sum method but getting type mismatch
expect to show sum of each configuration thread and their total sum in the end
[-1, -1]configuration 0
[-1, 1]configuration 1
[1, -1]configuration 2
[1, 1]configuration 3
all threads spawned
thread #, sum = 0 0
有人建议将返回值存储在数组中,然后将ID分配给每个线程,并使用Id作为数组的索引,不确定如何处理。任何帮助,将不胜感激,谢谢 **
class Magnetizationthread extends Thread {
public int sum;
public int len = 0;
Magnetizationthread(int n) {
len = n;
}
// Computes the total sum of all elements of the given array.
public static int sum(int a[]) {
int result = 0;
for (int i = 0; i < a.length; i++) {
result += a[i];
}
return result;
}
public List<List<Integer>> generateSequences(int seq_size) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
// for our recursion base case
if (seq_size == 1) {
List<Integer> new_seq_1 = new ArrayList<>(); // add -1 once
new_seq_1.add(-1);
List<Integer> new_seq_2 = new ArrayList<>(); // add 1 once
new_seq_2.add(1);
result.add(new_seq_1);
result.add(new_seq_2);
return result;
}
List<List<Integer>> sub_ans = generateSequences(seq_size - 1);
for (int i = 0; i < sub_ans.size(); ++i) {
List<Integer> new_seq_1 = new ArrayList<>(sub_ans.get(i)); // add -1 once
new_seq_1.add(-1);
List<Integer> new_seq_2 = new ArrayList<>(sub_ans.get(i)); // add 1 once
new_seq_2.add(1);
result.add(new_seq_1);
result.add(new_seq_2);
}
return result;
}
}