小编Use*_*rJS的帖子

使用5个线程添加数字

问题:我必须创建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) …
Run Code Online (Sandbox Code Playgroud)

java multithreading synchronized

1
推荐指数
1
解决办法
1万
查看次数

标签 统计

java ×1

multithreading ×1

synchronized ×1