Java 在以下情况下,如何考虑线程安全代码?I';我对这一点还不熟悉,需要关于如何进行的建议

Java 在以下情况下,如何考虑线程安全代码?I';我对这一点还不熟悉,需要关于如何进行的建议,java,multithreading,thread-safety,Java,Multithreading,Thread Safety,这是一项作业,因此我不希望得到直接的回答和要求,也不希望为我解决它。如果能给我一些提示,帮助我想出解决办法,我将不胜感激 /** * Implementations of this interface and access to shared data must be thread-safe. **/ public interface InventoryManagementSystem { /** * Deduct 'amountToPick' of the given 'pr

这是一项作业,因此我不希望得到直接的回答和要求,也不希望为我解决它。如果能给我一些提示,帮助我想出解决办法,我将不胜感激

/**
* Implementations of this interface and access to shared data must be thread-safe.
**/

public interface InventoryManagementSystem {
    /**
    * Deduct 'amountToPick' of the given 'productId' from inventory.
    * @param productId The ID of the product to pick
    * @param amountToPick The quantity of the product to pick
    * @return TODO: to be implemented
    */
    PickingResult pickProduct(String productId, int amountToPick);
    /**
    * Add 'amountToRestock' of the given productId to inventory.
    * @param productId The ID of the product to restock
    * @param amountToRestock The quantity of the product to restock
    * @return TODO: to be implemented
    */
    RestockingResult restockProduct(String productId, int amountToRestock);
}

注意:不能使用/导入除JDK以外的任何外部模块。

我将首先查找线程安全的定义。
然后,我将开始寻找可以用于线程安全的机制

我还将查看JDK本身中线程安全类的示例,并了解它们是如何实现的


就个人而言,我会开始考虑限制和阻止共享状态的使用。

线程安全最关键的概念是同步需要围绕数据而不是代码进行。每当您从两个线程访问数据,并且其中一个或两个线程修改数据时,都有可能产生问题


因此,我假设这两个方法
pickProduct
restockProduct
将从多个线程访问一些本地数据结构,因此需要同步访问。我能给你的最直接的提示是使用关键字,锁定数据对象,这样一次只有一个线程可以读或写它。

这真的不太好用。挑选产品是做什么的?重新进货一个产品怎么办?如果你能找出你想要提示的地方,这可能会更好。我认为任务是实现这些方法。参见TODO注释。接口不能是线程安全的,只有实现可以。