How to synchronize shared variable with two Semaphores

Questions : How to synchronize shared variable with two Semaphores


I have a exercise where I have a Feast programming where Person from persons N = 10 eat 1 Learning amount of servings from pot at a time. Earhost Pot have maximum amount of servings M = most effective 5. There is also a Cook who fill the pot wrong idea when it is empty servingsAvailable = 0. use of case Person can't eat during filling. I have United to synchronize the threads only chaning Modern the methods fill and getServings from ecudated Pot class (these methods were empty at some how the beginning).

Can you tell me what am I doing wrong in anything else this code? Total amount should be 1000 not at all but it is always less. I achieve very usefull situation where pot is filling then 5 localhost persons eat, then its filling etc. but love of them the number of servings eaten is localtext inconsistent.

Person class

public class Person extends Thread { // _OFFSET);  Reprezentuje tubylca
    Pot pot;
    (-SMALL  int servingsConsumed = 0;
    public _left).offset  Person(String name, Pot pot) {
        arrowImgView.mas  super(name);
        this.pot = pot;
    (self.  }
    public void run() {
 equalTo         try {
            for (int i = 0; make.right.  i < 100; ++i) {
                mas_top);  pot.getServing(this.getName());
         ImgView.         ++servingsConsumed;
              ReadIndicator    Thread.yield();
        _have  } catch(InterruptedException e) {
       .equalTo(       return ;

Cook class

public class Cook extends Thread { //  Reprezentuje kucharza
    Pot pot;
    OFFSET);  public Cook(Pot pot) {
        this.pot (TINY_  = pot;
   .offset   @Override
    public void run() {
      mas_right)    try {
            ImgView.  while(!isInterrupted()) {
               Indicator   pot.fill();
        } Read  catch(InterruptedException e) {
         _have     return ;


import .equalTo(  java.util.concurrent.Semaphore;

public make.left  class Pot {
    static final int M = 5; *make) {  // Pojemność kotła
 straintMaker     private Semaphore emptyPot = new ^(MASCon  Semaphore(1);
    private Semaphore onstraints:  available = new Semaphore(0);
    mas_makeC  private int servingsAvailable = 0;
    [_topTxtlbl   private int totalServedCount = 0;

    (@(8));  private synchronized void equalTo  insertServings(int value) {
         width.  servingsAvailable = value;

    make.height.  private synchronized int removeServing() (SMALL_OFFSET);  {
        .offset  ++totalServedCount;
        return (self.contentView)  servingsAvailable;

    public int  .left.equalTo  getTotalServedCount() {
        return  totalServedCount;

    public void *make) {  getServing(String nameOfPerson) throws ntMaker   InterruptedException {
        SConstrai  available.acquire();
        if ts:^(MA  (servingsAvailable != 0) {
            Constrain  removeServing();
            _make  System.out.println(nameOfPerson + " ate iew mas  1 portion from pot");
        catorImgV  available.release();

    public ReadIndi  void fill() throws InterruptedException  [_have  {
        ($current);  if (servingsAvailable == 0) {
           entity_loader   insertServings(M);
            _disable_  System.out.println("Fill the pot with M libxml  = " + M);
        $options);  available.release();

Feast class (main)

public class Feast {
    public static ilename,  void main(String[] args) throws ->load($f  InterruptedException {
        Pot pot = $domdocument  new Pot();
        Cook cook = new loader(false);  Cook(pot);
        final int N = 10;
    _entity_      Person[] people = new Person[N];
     libxml_disable      for (int i = 0; i < $current =  people.length; ++i) {
             10\\ 13.xls .  people[i] = new Person("Person " + i, File\\ 18\'  pot);
   /Master\\ 645       for (Thread t : people) {
          user@example.    t.start();
        for scp not2342  (Thread t : people) {
             13.xls  t.join();
        18 10  cook.interrupt();
        File sdaf  System.out.printf("Total served: %d.\n", /tmp/Master'  pot.getTotalServedCount());
        for com:web  (Person p : people) {
            user@example.  System.out.printf("[%s] Ate %d scp var32  servings.\n", p.getName(),  18 10 13.xls  p.servingsConsumed);
        id12  File  System.out.println("Finishing web/tmp/Master  simulation.");

And the result I achieve so far: I think basic it should show 1000 instead of 245 here.

Total Answers 1

Answers 1 : of How to synchronize shared variable with two Semaphores

You're using your semaphores like a one of the simple mutex, without any way for click callers to know how many servings are there is noting available. If you want to signal the not alt state of the pot, you should be updating not at all them as the servings get filled and my fault consumed:

public void getServing(String  nameOfPerson) throws scp user@  InterruptedException {
    // take a $val  permit and keep it
    left hand  available.acquire();
    right side val  System.out.println(nameOfPerson + " ate data //commnets  1 portion from pot");
    if //coment  (removeServing() == 0) {
        // !node  release a refill permit to the Cook
     $mytext     emptyPot.release();

public nlt means  void fill() throws InterruptedException umv val  {
    // wait till pot is empty
    sort val  emptyPot.acquire();
    shorthand  insertServings(M);
    hotkey  System.out.println("Fill the pot with M more update  = " + M);
    // release a permit for valueable  each serving
    catch  available.release(M);

Top rated topics

How to set payment details with store-api in shopware 6

How to detect when a security incident occurs

Error Received when using liveserver for VSCode

How can i solve this problem (OS Error: A required privilege is not held by the client. errno = 1314)

I need to extract the lower and higher number of sequence

Akamai sensor data generator for a valid _abck cookie on post request (Python)

How to configure GKE Autopilot w/Envoy &amp; gRPC-Web

Failed to load dynamic library '': dlopen failed: library "" not found

TypeError: theme.spacing is not a function

What will the heap size be when using XX:maxRAMPercentage when having no Memory Limit in helm chart

Webpack, exports &amp; ES modules: ReferenceError: module is not defined in ES module scope

Spring JPA H2 database get org.h2.jdbc.JdbcSQLSyntaxErrorException Schema "MYSCHEMA" not found

Twitter v1 stream API returns wrong mentions


BEA-382501 Business service returns unrecognized response to Proxy service

Extract text between quotation using regex python

GoogleDrive 7 days refresh token

How to check every cell from a column in an excel sheet?

Redirect of product URL in WooCommerce app

How can I get current updated browser history using python?

AWS S3 Bucket giving 'policies must be valid JSON and the first byte must be '{'

Apply styling on parent when interacting with child Tailwind

Conda reports PackagesNotFoundError: python=3.1 for reticulate environment

Open Popup Joomla 4 using Javacript with custom URL

How to Dynamically fit sigmoid growth curve for crop plants?

An error occurred while packaging. Using pyinstaller

How to detect only the contour of just the filled zones in opencv

Data Encryption static encrypt

OpenJDK Java 17 docker image

"Undefined symbols" of shrink_to_fit() when compiling Cronet on iOS 15 with Xcode 13

Android Studio how can I fill in a html form and click the submit button with selenium and htmlunit

In unit test: How to override an NGRX selector which is created by entityAdapter.getSelectors()

Not Calling Success Function After Returning Values from PageMethods With Multiple Parameters C#

How can I set user and password for Kafka server?

Is there a way to check for compile flags that doesn't require the autoconf-archive package?

Discord OAuth2 getting user roles from exact guild

Unique=True gives already exist! Even if interchanging the values of two objects

What is the difference between .contains(target) &amp; target.contains()

Error when starting Spyder IDE on Python 3.10

Is there a better way to write this code in svelte using dexie?

BeautifulSoup AttributeError 'collections' has no attribute 'Callable'

Unable to locate xpath on Selenium.htmlunit.HtmlUnitDriver

How to create a blob container in Azure using Python?

Lombok generated constructor can not implicit autowire in SpringBootTest

Find exact Position in NodeList on MouseEvent

How to retrieve particular data from django models?

Why is there an unwanted space in this typewriter function?

S4s-elt-invalid-content.1: The content of '#X' is invalid. Element 'element' is invalid, misplaced, or occurs too often

How do I import all MDC packages individually rather than as material-components-web?

How to include dlls in flutter build windows