Synchronized
Explore how to properly use synchronized blocks in Java multi-threading and understand common mistakes like reassigning synchronized objects. This lesson helps you avoid IllegalMonitorState exceptions by revealing issues with object synchronization and thread communication.
We'll cover the following...
We'll cover the following...
1.
What is synchronized?
Show Answer
Did you find this helpful?
Technical Quiz
1.
Consider the code snippet below:
class NewbieSynchronization {
Boolean flag = new Boolean(true);
public void example() throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
public void run() {
synchronized (flag) {
try {
while (flag) {
System.out.println("First thread about to sleep");
Thread.sleep(5000);
System.out.println("Woke up and about to invoke wait()");
flag.wait();
}
} catch (InterruptedException ie) {
}
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
flag = false;
System.out.println("Boolean assignment done.");
}
});
t1.start();
Thread.sleep(1000);
t2.start();
t1.join();
t2.join();
}
}
What will happen when the example() method is invoked? Select the most accurate answer.
A.
InterruptedException is thrown
B.
IllegalMonitorStateException is thrown
C.
Program runs without issues
D.
Thread t2 doesn’t synchronize on the same object as thread t1
1 / 1
A classic newbie ...