简体   繁体   English

我如何同步该程序

[英]How do i synchronize this program

I'm trying to write a program that launches 1000 threads. 我正在尝试编写一个启动1000个线程的程序。 Each Thread adds 1 to a variable sum that is initially 0. Doing this by passing sum by reference to each thread and I am told to do this using an Integer wrapper object to hold sum. 每个线程将1加到最初为0的变量总和上。通过将总和通过引用传递给每个线程来实现,并被告知要使用整数包装器对象来保存总和。

Code: 码:

public class synchronizedsum {
    public static void main(String args[]){
        int sum=0;
        ExecutorService executor = Executors.newCachedThreadPool();
        for(int i=0;i<1000;i++){
            executor.execute(new Adder(sum));
        }
        executor.shutdown();
        while(!executor.isTerminated()){

        }
        System.out.println(sum);
}
private static class Adder implements Runnable{
    private int sum;
    Adder(int sum){
        this.sum = sum;
    }

    public synchronized void run(){
        sum+=1;
    }
}
}

I think I've got something wrong cause does not seem to be working. 我认为我出了点问题,原因似乎不起作用。

EDIT: I keep getting output as 0 instead of 1000 that is the problem. 编辑:我一直在输出为0而不是1000这是问题。

EDIT: I tried doing this seems to give me right output but not sure if it meets the condition of passing sum by reference to each Thread. 编辑:我试图这样做似乎给我正确的输出,但不确定是否满足通过引用每个线程传递总和的条件。

CODE: 码:

public class synchronizedsum {

    private static Interger obj = new Interger();
    public static void main(String[] args) {

        ExecutorService executor = Executors.newCachedThreadPool();
        for(int i=0;i<1000;i++){
            executor.execute(new Add1());
        }
        executor.shutdown();
        while(!executor.isTerminated()){

        }
        System.out.println(obj.getSum());
    }
private static class Interger{
    private volatile int sum =0;
    private Lock lock = new ReentrantLock();
    public void add(int amount){
        lock.lock();
        try {
            sum+=amount;
            Thread.sleep(5);
        } catch (InterruptedException ex) {
            Logger.getLogger(Practice.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            lock.unlock();
        }
    }
    public int getSum(){
        return sum;
    }

}
public static class Add1 implements Runnable{

    public  void run(){
        obj.add(1);
    }
}
}

Will passing an AtomicInteger instead of an Integer help? 传递AtomicInteger而不是Integer会有所帮助吗? You won't have to deal with synchronized methods as updating the value for AtomicInteger guarantees that for you. 您不必处理synchronized方法,因为更新AtomicInteger的值可以为您保证这一点。

Above code is needlessly complex. 上面的代码不必要地复杂。 You can achieve it with a simple solution using AtomicInteger 您可以使用AtomicInteger通过简单的解决方案来实现

Few suggestions: 几点建议:

  1. Change newCachedThreadPool() to newFixedThreadPool(Runtime.getRuntime().availableProcessors()); newCachedThreadPool()更改为newFixedThreadPool(Runtime.getRuntime().availableProcessors());

  2. Use incrementAndGet of AtomicInteger by removing Lock 通过删除Lock使用AtomicInteger的增量和获取

You can refer to example code at this post and modify your code accordingly. 您可以在本文中参考示例代码,并相应地修改您的代码。

How can I access the property value of a running Thread 如何访问正在运行的线程的属性值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM