Displaying a simple example of a dead end with semaphores

Currently, I take operating systems, and our teacher assigned this problem to our laboratory, but it is not very useful. Therefore, I need to show a basic example of a dead end with semaphores, and my conclusion should demonstrate the occurrence of a dead end. I assume it means my exception is caught. It is as close as I received.

import java.util.concurrent.Semaphore;
public class deadlockTest2
{
    private Semaphore sem1=new Semaphore(1);
    private Semaphore sem2=new Semaphore(1);
    private int num;

    public deadlockTest2(int random)
    {
            num=random;
    }
    public void run()
    {
        try 
        {
            sem1.acquire();
        }
         catch (InterruptedException e)
        {
            System.out.println("I am deadlocked");}
        }

    public static void main(String[] args)
    {
        deadlockTest2 tester=new deadlockTest2(5);
        deadlockTest2 tester2=new deadlockTest2(20);
        tester.run();
        tester2.run();
    }   
}

~
~
Am I even close? I continue to read the material, but do not fully understand it. I think I do not understand what a process is. Someone please help.

+4
source share
1 answer

, . ; .

, , , . :

  • A Mutex A
  • B Mutex B
  • A Mutex B, B!
  • B Mutex A, A!

. - 1.

, , , . .

, , , , , . :

  • A Mutex A_A ( A)
  • B Mutex B_B ( B)
  • A Mutex B_A ( A)
  • B Mutex A_B ( B)

, ( Mutex A Mutex B) .

, , :

Semaphore sem1 = new Semaphore(1);
Semaphore sem2 = new Semaphore(1);

public class deadlockTest1 implements Runnable
{
    public void run()
    {
        sem1.acquire();
        Thread.sleep(1000);
        sem2.acquire();
    }
}

public class deadlockTest2 implements Runnable
{
    public void run()
    {
        sem2.acquire();
        Thread.sleep(1000);
        sem1.acquire();
    }
}

:

public static void main(String[] args)
{
    deadlockTest1 tester1 = new deadlockTest1();
    deadlockTest2 tester2 = new deadlockTest2();
    tester1.run();
    tester2.run();
}

, . , ( sem1, B lock sem2), 1 . ( sem2, B sem1), , , .

+2

Source: https://habr.com/ru/post/1544803/


All Articles