Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easier way to synchronize 2 threads in Java?

I wan't to be sure that some piece of my code within the main thread will be executed after some piece of code executed withing the secondary thread. Here's what I got:

    final Object lock = new Object();
    final Thread t = new Thread(new Runnable() {
        public void run() {
            synchronized(lock) {
                System.out.println("qwerty");
                lock.notify();
            }
        }
    });

    synchronized(lock) {
        t.start();
        lock.wait();
    }

    System.out.println("absolutely sure, qwerty is above");
  1. Is it correct solution?
  2. Any shorter ways to do the same?
like image 423
Andrey Agibalov Avatar asked Aug 12 '11 15:08

Andrey Agibalov


People also ask

What is the alternative to synchronized in multi threading?

concurrent package has a whole range of classes that can be used to make multi-threaded code thread-safe without explicitly using the "synchronized" keyword, if that's what you're asking. The ThreadLocal class may also help, as may the "volatile" keyword.

Which is used for synchronizing multiple threads?

Java provides a way of creating threads and synchronizing their task by using synchronized blocks.


1 Answers

Things like notify() and wait() are really low-level synchronization primitives.

You should use higher-level abstractions whenever possible, like in this case, say, a CountDownLatch.

The following is just an example that should get you started (for example the timeout issues aren't taken into account here):

    final CountDownLatch latch = new CountDownLatch(1);
    final Thread t = new Thread(new Runnable() {
        public void run() {
            System.out.println("qwerty");
            latch.countDown();
        }
    });

    t.start();
    latch.await();

    System.out.println("absolutely sure, qwerty as been printed");

Low-level things like wait and notify are really just low-level Java idiosynchrasies that you shouldn't be concerned with (unless you're writing concurrency APIs).

Additionally, I'd suggest reading the amazing book: Java Concurrency In Practice.

like image 175
SyntaxT3rr0r Avatar answered Oct 05 '22 22:10

SyntaxT3rr0r