私は、原子整数または同期を使用する必要があります

Sprint21:

私は私のコードでは、原子/揮発性/同期を使用する方法について混乱少しを持っています。のは、私は書店での書籍情報のオブジェクトを持っており、例えば、それは2つのスレッドがインベントリに量が唯一の1である一方、同じ本を撮りたいということが起こることがあり、どのように私は1つのスレッドだけ本を取ることを約束することができましょう?私は、同期を使用する必要がありますか?BookInventoryInfo:

package bgu.spl.mics.application.passiveObjects;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Passive data-object representing a information about a certain book in the inventory.
 * 
 * <p>
 *
 */
public class BookInventoryInfo {

    //The title of the book, his amount in the inventory and the price
    private String bookTitle;
    private AtomicInteger amountInInventory;
    private int price;

    public BookInventoryInfo(String bookTitle, int amountInInventory, int price) {
        this.bookTitle = bookTitle;
        this.price = price;
        this.amountInInventory = new AtomicInteger(amountInInventory);
    }


    /**
     * Retrieves the title of this book.
     * <p>
     * @return The title of this book.   
     */
    public String getBookTitle() {
        return this.bookTitle;
    }

    /**
     * Retrieves the amount of books of this type in the inventory.
     * <p>
     * @return amount of available books.      
     */
    public int getAmountInInventory() {
        return this.amountInInventory.get();
    }

    /**
     * Retrieves the price for  book.
     * <p>
     * @return the price of the book.
     */
    public int getPrice() {
        return this.price;
    }

    public void reduceAmountInInventory() {
        this.amountInInventory.decrementAndGet();
    }
}

私は本を​​取るために望む方法:

if(book.getAmountInInventory > 0)
{
    book.amountInInventory--
}
ピーターLawrey:

あなたは使用する必要があるsynchronizedのAtomicIntegerを使用すると、それは一見見えるかもしれないような単純なようではありませんよう。AtomicInteger上の個々の操作はスレッドセーフですが、複数の操作を使用することはないかもしれません。あなたの例では、良いものです。あなたが持っていると言います

// say it start at 1
Thread1: if(book.getAmountInInventory > 0)
Thread2: if(book.getAmountInInventory > 0)
Thread1: book.amountInInventory--
Thread2: book.amountInInventory--

量は今ある-1。

あなたが使用している場合synchronizedには、全体の動作のためにロックを保持するためにはるかに簡単です

synchronized (book) {
    if(book.getAmountInInventory > 0) // no chance for a race condition here.
    {
        book.amountInInventory--
    }

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=221782&siteId=1