使用5个线程添加数字

Use*_*rJS 1 java multithreading synchronized

问题:我必须创建5个线程,每个线程必须执行添加操作.

  • Thread1 - 添加1到10
  • Thread2 - 添加1到50
  • Thread3 - 添加5到15
  • Thread4 - 添加10到20
  • Thread5 - 添加15到20

完成此任务的最佳方法是什么?此外,每次加法操作之间需要1秒的时间延迟.我写了这段代码:我的输出错了,每次都在改变.我知道问题是同步但不能解决.

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

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 
Run Code Online (Sandbox Code Playgroud)

Iły*_*sov 11

这是问题所在:

sum = sum + a;
Run Code Online (Sandbox Code Playgroud)

它应该是 sum += i;

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

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