Conteúdo do Curso
Multithreading in Java
Multithreading in Java
Challenge Lock и Condition
Task Description
Imagine you are designing a traffic light controller for a busy intersection. The traffic light system consists of three stages: red light, yellow light, and green light. These stages must be executed in a specific order to ensure safe and efficient traffic flow.
Your task is to implement the methods: redLight()
, yellowLight()
, and greenLight()
. These methods must be executed strictly in the order of a real traffic light: first red light, then yellow light, and finally green light, regardless of the order in which threads call them.
Requirements:
- Synchronization: Ensure that methods are executed in strict order;
- Multithreading: Methods can be called from different threads, but execution must occur in the order:
redLight()
,yellowLight()
, andgreenLight()
; - Use Lock and Condition: Apply
Lock
to control access to shared resources andCondition
to coordinate threads.
Hint
The
counter
field in theTaskLockExample
class is specified for a reason, you will need to check its value in each method and depending on what is there you decide whether to start this thread or not.
You also need to use the lock
and condition
fields to lock some thread and decide who will be first, second, third.
Once you have implemented the methods and moved to the Main
class and run its main method, you should have an output no matter in what order and which thread runs which method.
Also print something to the console to check if the methods are executed in the correct order.
Note
You can also swap the start of threads (not the implementation itself, but where the thread's
start()
method is called)
Once you are sure that everything is working, run the verification tests on the path /src/test/java/TaskLockExampleTest.java
.
Obrigado pelo seu feedback!