Kappa
Kappa

Reputation: 35

Java Multi threading semaphore

The counter variable does not accurately reflect how many times increment method is invoked. Why not, and how can it be fixed? (You do not have to write code, just use English.)

Original:

import java.util.*;
import java.lang.*;
import java.io.*;


class Foopadoop
{
public static int counter = 0;
public static void main(String[] args) throws Exception {
    Runnable r = new Runnable() {
        public void run() {
            while(true){
                counter++;
            }
        }
    };
    Thread t1 = new Thread(r);
    Thread t2 = new Thread(r);
    t1.start();
    t2.start();
}
}

Mine, I added a semaphore but I'm not sure if I'm doing it right or am I suppose to use a lock.

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.concurrent.Semaphore;

class Foopadoop
{
public static int counter = 0;
Semaphore lock = new Semaphore(0);
public static void main(String[] args) throws Exception {
    Runnable r = new Runnable() {
        try{public void run() {
            while(true){
                counter++;
                lock.acquire();
            }
        }
       }finally{
         lock.release();
        }
    };
    Thread t1 = new Thread(r);
    Thread t2 = new Thread(r);
    t1.start();
    t2.start();
}
}

Upvotes: 3

Views: 1644

Answers (2)

Sanushi Salgado
Sanushi Salgado

Reputation: 1436

Also you can add Thread.sleep(ms) inside the while loop, so that it will pause the current thread for some time, & start executing other threads. Otherwise the current thread might run in a selfish manner (selfish thread).

Upvotes: 0

Andy Turner
Andy Turner

Reputation: 140299

That's not how you use a Semaphore.

You acquire it before you access the shared resource, and release it after:

while (true) {
  try {
    lock.acquire();
    counter++;
  } finally {
    lock.release();
  }
}

Since you acquire first, you will also need at least 1 permit, otherwise there is nothing to acquire:

static Semaphore lock = new Semaphore(1);

A synchronized block is easier than a Semaphore:

while (true) {
  synchronized (Foopadoop.class) {
    counter++;
  }
}

or an AtomicInteger:

static AtomicInteger counter = new AtomicInteger();

// ...

while (true) {
  counter.getAndIncrement();
}

Upvotes: 4

Related Questions