Challenge Semaphore
Task
Imagine you have a resource that can be accessed by only two threads at a time. Your task is to create a program that uses a semaphore to control access to this resource.
Conditions:
- You have a
Resourceclass with ause()method that simulates the use of a resource, such as printing a message and introducing a delay; - You have a
Workerclass that implementsRunnable; in itsrun()method, it will attempt to access the resource using asemaphore; - In the
SemaphoreExampleclass, you have amain()method that initializes asemaphorewith permits for two threads, along with multiple worker threads that will attempt to access the resource; - Ensure that no more than two threads can use the resource at any given time.
How should the program work?
You have 5 threads that want to execute the use() method simultaneously, but with a Semaphore, you need to limit the simultaneous execution to 2 threads. As soon as a thread releases the Semaphore, another thread can begin executing this method. For better clarity in this scenario, it’s recommended to introduce a delay within the use() method.
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo
Awesome!
Completion rate improved to 3.33
Challenge Semaphore
Deslize para mostrar o menu
Task
Imagine you have a resource that can be accessed by only two threads at a time. Your task is to create a program that uses a semaphore to control access to this resource.
Conditions:
- You have a
Resourceclass with ause()method that simulates the use of a resource, such as printing a message and introducing a delay; - You have a
Workerclass that implementsRunnable; in itsrun()method, it will attempt to access the resource using asemaphore; - In the
SemaphoreExampleclass, you have amain()method that initializes asemaphorewith permits for two threads, along with multiple worker threads that will attempt to access the resource; - Ensure that no more than two threads can use the resource at any given time.
How should the program work?
You have 5 threads that want to execute the use() method simultaneously, but with a Semaphore, you need to limit the simultaneous execution to 2 threads. As soon as a thread releases the Semaphore, another thread can begin executing this method. For better clarity in this scenario, it’s recommended to introduce a delay within the use() method.
Obrigado pelo seu feedback!