对于我的大学课程,我们刚开始并行编程,但是,我已经完成了计算并行执行任务所需时间的任务。现在我已经知道我需要使用“System.currentTimeMillis();”的实例。确保这一点有效,我还需要在执行任务之前以及之后执行此操作,以确定它初始化所需的时间。这让我很困惑,因为每次尝试实现这一点时,我都会得到完全相同的时间,而且我认为我没有正确实现它。任何帮助都会非常感激,因为我似乎无法使用Java获得“点击”。
很抱歉,如果我没有正确格式化等等。
这是我的主要课程:
import java.util.*;
import java.lang.*;
public class Main {
public static void main(String[] args) {
// Define a new array
ArrayList<Integer> L = new ArrayList<Integer>(100);
// Initialise the array with random values between 0 and 100
Random R = new Random();
for (Integer i=0; i<100; i++) {
L.add(R.nextInt(10));
}
for (Integer i=0; i<100; i++) {
System.out.print(L.get(i));
System.out.print(", ");
}
System.out.println("");
// Process the array
Thread doubler1 = new Doubler(L, 0, 50);
Thread doubler2 = new Doubler(L, 50, 100);
doubler1.start();
doubler2.start();
try {
doubler1.join();
doubler2.join();
}
catch(InterruptedException e) {}
for (Integer i=0; i<100; i++) {
System.out.print(L.get(i));
System.out.print(", ");
}
}
}
这是我的Doubler课程:
import java.util.*;
import java.lang.*;
public class Doubler extends Thread {
// We'll store a reference to the list we want to process
// (all instances could see the same list)
private ArrayList<Integer> L;
// Store the range within the array we want to process
private int startIndex, endIndex;
// Constructor to initialise Doubler instance - this stores a reference to the list to process
// and the start and end indices to process when the thread is run.
public Doubler(ArrayList<Integer> list, int start, int end) {
L = list;
startIndex = start;
endIndex = end;
}
// Run this on a thread - managed by the JRE
public void run() {
// Process the range of integers by doubling each value
for (int i=startIndex;i<endIndex;i++) {
L.set(i, L.get(i) *2);
}
}
}
答案 0 :(得分:0)
System.currentTimeMillis()
可能会返回同一时间。由于您不得不以这种方式测量时间,因此您需要更改线程以使它们执行更长的任务,以便可以准确地测量时间。