Synchronized
This lesson explains the all-important synchronized keyword.
We'll cover the following...
We'll cover the following...
1.
What is synchronized?
0/500
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 be the output of invoking the example()
method ?
A.
InterruptedException is thrown
B.
IllegalStateException is thrown
C.
Program runs without issues
D.
Thread t2 doesn’t synchronize on the same object as thread t1
1 / 1
Java
class Demonstration {public static void main( String args[] ) throws InterruptedException {(new NewbieSynchronization()).example();}}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();}}
A classic ...