Java locks CountDownLatch family for a meal

Source: Internet
Author: User

Recently, I have been writing a Java concurrency example to share it with you and strengthen my memory.

Every day when I go to work, my parents also go to work, saying that I have set up a hotel today, and my family will have a meal together to inform everyone to go to the hotel after work. Assume that three people go to work in different places, and they have to wait until three people arrive to have dinner. How can this problem be achieved through a program?

As a senior diaosi programmer, I started to write code for implementation:

Package com. zhy. concurrency. latch; public class Test1 {/*** simulate dad going to the hotel */public static void fatherToRes () {System. out. println ("it takes 3 hours for Dad to walk to the hotel. ");}/*** Simulate my trip to the Hotel */public static void motherToRes () {System. out. println (" Mom needs 2 hours to take the bus to the hotel. ");}/*** Simulate mom going to the hotel */public static void meToRes () {System. out. println (" it takes me one hour to take the subway to the hotel. ");}/*** Simulate the arrival of a family */public static void togetherToEat () {System. out. println ("family arrives, start eating");} public static void main (String [] args) {fatherToRes (); motherToRes (); meToRes (); togetherToEat ();}}

Output result:

Dad needs 3 hours to walk to the hotel. It takes two hours for Mom to squeeze the bus to the hotel. It takes me one hour to take the subway to the hotel. The family is ready to eat.

It seems to have been done, but it took six hours to have a meal and waited three hours for the first arrival, it's also a parallel process, so I don't need to say that everyone will think of using multithreading, so as a Senior Programmer, we started to transform our code:

public static void main(String[] args){new Thread(){public void run(){fatherToRes();};}.start();new Thread(){public void run(){motherToRes();};}.start();new Thread(){public void run(){meToRes();};}.start();togetherToEat();}

Three threads are started directly, but the running result does not seem to be correct:

My family arrived, and it took me an hour to take the subway to the hotel. It takes two hours for Mom to squeeze the bus to the hotel. Dad needs 3 hours to walk to the hotel.

When I did not arrive, I began to eat ). If not, continue to improve:

private static volatile int i = 3;public static void main(String[] args){new Thread(){public void run(){fatherToRes();i--;};}.start();new Thread(){public void run(){motherToRes();i--;};}.start();new Thread(){public void run(){meToRes();i--;};}.start();while (i != 0);togetherToEat();}

We have defined a volatile modified int type variable with the initial value of 3. When the table family is ready for use in the ERA 0, we have used a busy schedule in the main thread, waiting for everyone to arrive, this time it looks good:

It takes me one hour to take the subway to the hotel. It takes two hours for Mom to squeeze the bus to the hotel. Dad needs 3 hours to walk to the hotel. The family is ready to eat.
However, busy waiting for such code consumes too much CPU, and we need a better implementation method. By the way, why do we use volatile to modify I? Because when multiple threads operate on the same variable, synchronization must be used to ensure the visibility of variable modifications to other threads, volatile is a good choice for implementing visibility, But I in our code may also cause some problems due to concurrency. After all, I is not an atomic operation, normally, it is best to use a synchronization block or AtomicLong. decrementAndGet () Implementation --.

After talking about this, the CountLatchDown on the title did not appear, so the final version must make this buddy Debut:

private static CountDownLatch latch = new CountDownLatch(3);public static void main(String[] args) throws InterruptedException{new Thread(){public void run(){fatherToRes();latch.countDown();};}.start();new Thread(){public void run(){motherToRes();latch.countDown();};}.start();new Thread(){public void run(){meToRes();latch.countDown();};}.start();latch.await();togetherToEat();}

Output result:

It takes me one hour to take the subway to the hotel. It takes two hours for Mom to squeeze the bus to the hotel. Dad needs 3 hours to walk to the hotel. The family is ready to eat.
To avoid being busy, we use CountDowmLatch to meet our needs. The following describes this Buddy:

Latch locking refers to a synchronization tool class. Similar to a door: the door is closed until it reaches the end state, and no thread is allowed to pass through. When it reaches the end state, this door will open and allow all threads to pass. When the door is opened, it is always open.

Purpose: it can be used to ensure that certain activities are not executed until other activities are completed.

Use Cases:

1. For example, in our previous example, all of us arrived at the hotel and had dinner;

2. The resources required for an operation have been initialized.

3. All threads on which a service depends are enabled...

CountDowmLatch is a flexible locking implementation that includes a counter. This calculator is initialized to a positive number, indicating the number of events to wait. CountDown indicates that an event occurs and the await method waits for the counter to reach 0, indicating that all the tasks to be waited have been completed.


All right, complete ~ Let me give you a speech to increase my motivation ~


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.