简体   繁体   中英

facing Java multithread concurrency issue

I have created three thread like client1, client2, client3 with corresponding read request "read 2", "read 1", "read 3". i wanted to process a read request in following manner:

Client2 read 1

Client1 read 2

Client3 read 3

i don't have idea to run a thread (client2) first and then thread (client1) and so on based on read request sequence.There is a one condition that i can't use sleep in my program.

Please provide help in above context of problem if anyone know about the solution.

Depending on the complexity of your program, it could be done using 2 CountDownLatch to synchronize your threads, one to release Client1 once Client2 has done reading and another one to release Client3 once Client1 has done reading.

// Used to release client1 
CountDownLatch startThread1 = new CountDownLatch(1);
Thread client2 = new Thread(
    () -> {
        System.out.println("Read 1");
        // Release client1
        startThread1.countDown();
    }
);
// Used to release client3
CountDownLatch startThread3 = new CountDownLatch(1);
Thread client1 = new Thread(
    () -> {
        try {
            // Waiting to be released
            startThread1.await();
            System.out.println("Read 2");
            // Release client3
            startThread3.countDown();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
);
Thread client3 = new Thread(
    () -> {
        try {
            // Waiting to be released
            startThread3.await();
            System.out.println("Read 3");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
);
// Start the threads in reverse order intentionally to show that 
// we still have the expected order
client3.start();
client1.start();
client2.start();

Output:

Read 1
Read 2
Read 3

This approach guarantees to get the correct read sequence whatever the order of the start sequence of your threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM