简体   繁体   中英

Java concurrency barrier example deadlock

I am trying to implement custom Barrier example in order to learn more about concurrency in Java. I have a runnable class:

public class Barrier implements Runnable {

    private static Semaphore barrier = new Semaphore(0);
    private static int toWait = 5;
    private static int counter = 0;

    private static long sleepTime;

    public static int ID = 0;

    private int id = ++ID;

    public Barrier(long sleep){
        sleepTime = sleep;
    }

    @Override
    public void run() {

        try {

            Thread.sleep(sleepTime);

            counter++;
            if (counter == toWait){
                barrier.release(counter);
            }
            barrier.acquire();

            System.out.println("Thread with sleep: " + id + " proceeds");

        } catch (InterruptedException ex) {
            Logger.getLogger(Barrier.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

}

Then in the main function, I create 5 threads and start them. Upon, running I get a deadlock, that I can't resolve. Can someone tell me what I am doing wrong?

See the documentation:

Acquires a permit, if one is available and returns immediately, reducing the number of available permits by one.

If no permit is available then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of two things happens:

Some other thread invokes the release() method for this semaphore and the current thread is next to be assigned a permit; or Some other thread interrupts the current thread.

So since you are aquire 'ing all threads once and none of them is released they'll all stay aquired. Maybe set the Counter on of of them to 5. So you release the last element and remove the aquire state of the other elements by doing this.

Edit: oh and your Semaphore has 0 permits. Initiatialize it with 1 or 2 for your case.

There were no mutual exclusion. To solve it, I needed to add another semaphore and surround the counter increment with with acquire release of that semaphore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM