多线程环境中的增量和减量 [英] Increments and decrements in multi threaded environment

查看:93
本文介绍了多线程环境中的增量和减量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在多线程环境中对int变量进行经典的递增/递减。这是我的示例代码。

I am trying the classic increment/decrement of an int variable in a multi threaded environment. This is my sample code.

public class SyncIncDec {


    public static void main(String[] args) {

        SyncCounter count = new SyncCounter();

        Thread incThread = new Thread(() -> {
            count.increment();
        });

        Thread decThread = new Thread(() -> {
            count.decrement();
        });

        Thread displayThread = new Thread(() -> {
            System.out.println("Count value : " + count.getX());
        });

        incThread.start();
        decThread.start();
        displayThread.start();      

        try {
            incThread.join();
        } catch (InterruptedException e) {
//          e.printStackTrace();
        }

        try {
            decThread.join();
        } catch (InterruptedException e) {
//          e.printStackTrace();
        }

        try {
            displayThread.join();
        } catch (InterruptedException e) {
//          e.printStackTrace();
        }

    }

}


class SyncCounter {

    private int x=0;

    public SyncCounter() {
        super();
    }

    public SyncCounter(int y) {
        super();
        x = y ;
    }

    synchronized int  getX() {
        return x; 
    }

    void setX(int y) {
        x = y ;
    }

    void increment() {
        ++x;
    }


    void decrement() {
        --x;
    }

}

尽管我使用过join()对于所有三个线程的方法,我仍然得到不一致的结果。
不是在这里加入意味着主线程要等到每个线程都完成执行吗?我什至尝试将同步添加到三个方法签名中的每个;但是我得到不一致的结果。

Though I have used join() method for all the three threads, I still get inconsistent results. Doesn't join here mean for the main thread to wait until each of the thread has completed its execution? I even tried adding synchronized to each of three method signatures; yet I get inconsistent results.

除了使用原子版本的变量外,我还能如何确保始终获得0?

Apart from using Atomic version of the variable, how else can I ensure that I get 0 always?

推荐答案

您的SyncCounter根本不是线程安全的。可变方法的增量和减量应同步。现在,实现此类的正确方法是在原子演说中。
例如:

Your SyncCounter is not thread safe at all. Mutable methods increment and decrement should be synchronized. Now days correct way to implement such a class would be in atomic orations. For example:

class SyncCounter {

    private final AtomicInteger x;

    public SyncCounter() {
     this(0);   
    }

    public SyncCounter(int x) {
       this.x = new AtomicInteger(x);
    }

    int getX() {
        return x.get(); 
    }

    void setX(int x) {
        this.x.set(x);
    }

    int increment() {
        return x.incrementAndGet();
    }


    int decrement() {
        return x.decrementAndGet();
    }

}

以及测试代码:

    final Thread incThread = new Thread(() -> {
        count.increment();
    });

    final Thread decThread = new Thread(() -> {
        count.decrement();
    });

    Thread displayThread = new Thread(() -> {
        incThread.join();
        decThread.join();
        System.out.println("Count value : " + count.getX());
    });

这篇关于多线程环境中的增量和减量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆