添加线程和打印运行时

时间:2016-12-11 19:06:31

标签: java multithreading

我的教授挑战我用Java编写程序以获得以下提示: “假设我们想要找到范围[1,100]内的整数之和。创建四个线程,每个线程计算25个整数的总和。打印出总和和程序运行时间.Thread1:[1, 25],Thread2:[26,50],Thread3:[51,75]和Thread4:[76,100]。“

我能够完成以下操作,但是,totalTime有时是先打印,有时是第二次打印等。我希望它最后打印,这可能吗?另外,为什么会发生这种情况?感谢您的时间!

我目前的代码:

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

1 个答案:

答案 0 :(得分:0)

它是线程所以它将独立执行不会以相同的顺序给出输出,每次序列可能会改变..!如果你想在最后执行该代码,请将其放在另一个线程中并使用join方法......!

相关问题