我受到教授的挑战,要求在Java中编写该程序,以获取以下提示:"假设我们想在范围内找到整数的总和[1,100]。创建四个线程,每个线程计算25个整数的总和。打印总和和程序运行时间。线程1:[1,25],thread2:[26,50],thread3:[51,75]和thread4:[76,100]。"
我能够完成以下内容,但是,总共有时是首先打印的,有时是第二个。我想在最后打印,这是可能的吗?另外,这为什么会发生?感谢您的时间!
我当前的代码:
public class ThreadAdding
{
public static void main(String[] args)
{
long startTime = System.currentTimeMillis();
Thread t1 = new Thread(new addition(1,25));
Thread t2 = new Thread(new addition(26,50));
Thread t3 = new Thread(new addition(51,75));
Thread t4 = new Thread(new addition(76,100));
t1.start();
t2.start();
t3.start();
t4.start();
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println("Total time for operations: " + totalTime);
}
}
class addition implements Runnable
{
int a,b;
public addition(int a, int b)
{
this.a = a;
this.b = b;
}
public void run()
{
add(a,b);
}
public void add(int a, int b)
{
int sum = 0;
synchronized (this)
{
for(int i = a; i <= b; i++)
{
sum += i;
}
System.out.println("Sum of numbers from " + a + " to " + b + " = " + sum);
}
}
}
它的线程,因此它将独立执行不会以相同的顺序给出输出,每次序列可能会更改。如果您想在最后执行该代码,则将其放在另一个线程中并使用加入方法...!