Reputation: 18221
Why usually threading samples put so many code in synchronized block. According to my understanding in following case synchronized is used just for locking b for wait and notify:
Main class ThreadA :
class ThreadA {
public static void main(String [] args) {
ThreadB b = new ThreadB();
b.start();
synchronized(b) {
try {
System.out.println("Waiting for b to complete...");
b.wait();
} catch (InterruptedException e) {}
System.out.println("Total is: " + b.total);
System.out.println(Thread.currentThread().getName());
}
}
}
and class ThreadB:
class ThreadB extends Thread {
int total;
public void run() {
synchronized(this)
{
System.out.println();
for(int i=0;i<100;i++)
{
System.out.println(Thread.currentThread().getName());
total += i;
}
notify();
}
}
}
What will change if I put just wait
and notify
in synchronized
block:
class ThreadA {
public static void main(String [] args) {
ThreadB b = new ThreadB();
b.start();
try {
System.out.println("Waiting for b to complete...");
synchronized(b) { b.wait();}
} catch (InterruptedException e) {}
System.out.println("Total is: " + b.total);
System.out.println(Thread.currentThread().getName());
}
}
Upvotes: 0
Views: 326
Reputation: 493
Expanding on the answer by @sk2212, the increment operation is not atomic, but there is an equivalent atomic operation provided in high-level concurrency primitives.
Upvotes: 0
Reputation: 1503260
According to my understanding in following case synchronized is used just for locking b for wait and notify
Your understanding is wrong.
synchronized
is also used for:
What will change if I put just wait and notify in synchronized block:
In this particular case, it will make a difference based on a race condition - in the original code, if the new thread
starts executing before the synchronized block is reached in the original thread, it won't get as far as "Waiting for b to complete" until the second thread has finished... at which point it will block forever in wait
.
Note that it's a really bad idea to wait on Thread
monitors, as wait/notify
is used internally by Thread
.
In short, the example you've used is a bad one to start with in various ways - but synchronization is used for more than just wait/notify
.
Upvotes: 3
Reputation: 1722
Please note that total += i
is not an atomic operation in Java. So you have to sync also this construct.
You also have not to sync notify() and wait() because their locks are handled internally.
Upvotes: 0