Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Challenge Lock и Condition | High-level Synchronization Mechanisms
Multithreading in Java
course content

Contenido del Curso

Multithreading in Java

Multithreading in Java

1. Multithreading Basics
2. Synchronized Collections
3. High-level Synchronization Mechanisms
4. Multithreading Best Practices

bookChallenge 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(), and greenLight();
  • Use Lock and Condition: Apply Lock to control access to shared resources and Condition to coordinate threads.

Hint

The counter field in the TaskLockExample 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.

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 3. Capítulo 2
some-alt