Spr*_*t21 2 java concurrency multithreading synchronization atomic
我在代码中使用原子/易失性/同步有点困惑.假设我在书店中有书信息的对象,例如,可能会发生两个线程想要同一本书,而库存中的金额只有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();
}
}
Run Code Online (Sandbox Code Playgroud)
我想拿这本书的方式:
if(book.getAmountInInventory > 0)
{
book.amountInInventory--
}
Run Code Online (Sandbox Code Playgroud)
您应该使用synchronizedAtomicInteger并不像初看起来那么简单.虽然AtomicInteger上的单个操作是线程安全的,但使用多个操作可能不是.你的榜样很好.说你有
// say it start at 1
Thread1: if(book.getAmountInInventory > 0)
Thread2: if(book.getAmountInInventory > 0)
Thread1: book.amountInInventory--
Thread2: book.amountInInventory--
Run Code Online (Sandbox Code Playgroud)
金额现在为-1.
如果使用synchronized它,可以更轻松地保持整个操作的锁定
synchronized (book) {
if(book.getAmountInInventory > 0) // no chance for a race condition here.
{
book.amountInInventory--
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
95 次 |
| 最近记录: |