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");
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.
Java provides a way of creating threads and synchronizing their task by using synchronized blocks.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With