使用 5 个线程添加数字

Add numbers using 5 threads

问题:我必须创建 5 个线程,每个线程都必须执行加法运算。

完成此任务的最佳方法是什么?另外,我需要在每次加法操作之间有 1 秒的时间延迟。我写了这段代码: 我的输出是错误的并且每次都在变化。我知道问题出在 synchronized 但无法解决。

class adding implements Runnable{
    int a,b; 
    public adding(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 = sum+ a;
            }
            System.out.println("Sum of "+a+" to "+ b+" numbers = "+sum);    
        }
    }
}

public class addnumbersusing5threads {
    public static void main(String[] args) {
        Thread t1 = new Thread(new adding(1,10));
        Thread t2 = new Thread(new adding(1,50));
        Thread t3 = new Thread(new adding(5,15));
        Thread t4 = new Thread(new adding(10,20));
        Thread t5 = new Thread(new adding(15,20));
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
    }
}

输出:

Sum of 1 to 10 numbers = 10  
Sum of 1 to 50 numbers = 50 
Sum of 5 to 15 numbers = 55 
Sum of 10 to 20 numbers = 110 
Sum of 15 to 20 numbers = 90 

这是问题所在:

sum = sum + a;

应该是sum += i;

顺便说一句,这里不需要任何同步

如果你想在添加之间延迟 - 使用Thread.sleep(1000L);

Thread.sleep(1000L) 添加到您的添加方法

   public void add(int a, int b) throws InterruptedException {
        int sum=0;
        synchronized (this) {
            for(int i=a;i<=b;i++){
                sum += i;
                Thread.sleep(1000L); // Add this line for one second delay on each addition
            }
            System.out.println("Sum of "+a+" to "+ b+" numbers = "+sum);

        }
    }

根据 Lashane,这里不需要同步 - sum 上没有争用,因为每个线程都有自己的变量。 (如果您确实需要同步,don't synchronize on this 因为对象引用的范围在 class 之外,并且可能会遇到死锁 - 相反,在私有字段对象上同步,例如 private final Object lock = new Object();)

 public void add(int a, int b){
    int sum=0;
    for(int i=a;i<=b;i++){
        sum = sum + i;
        Thread.sleep(1000);
    }
    System.out.println("Sum of "+a+" to "+ b+" numbers = "+sum);
}

此外,启动线程后,您需要将它们重新加入主线程。

...
t4.start();
t5.start();
// Join
t1.join();
t2.join();
...