Good afternoon, I recently read Bruce Ekkel, and came across such a problem: the synchronized (Object) block blocks the object's class, it’s not the object itself. I came to this conclusion after executing this code:
public class Main { public static void main(String[] args) { Sync s = new Sync(); new Thread(new Runnable() { @Override public void run() { s.go(); } }, "First").start(); new Thread(new Runnable() { @Override public void run() { s.go(); } }, "Second").start(); } } class Sync { private Writer w1, w2; public Sync() { w1 = new Writer(); w2 = new Writer(); } public void go() { synchronized (w2) { w1.log(Thread.currentThread().getName() + "...1"); //!Этот блок кода должен выполнятся паралельно во всех потоках, но выполняется последовательно. w2.log(Thread.currentThread().getName() + "...2"); //Этот должен выполнятся последовательно, и он так и делает. } } } class Writer { public void log(Object obj) { for (int i = 0; i < 5; i++) { lgn(obj); try { TimeUnit.MILLISECONDS.sleep(750); } catch (InterruptedException e) { e.printStackTrace(); } } } } Why, when locking w2, does it block w1? These are different objects?
The book and all sources speak about locking in a synchronized object! If I did something wrong or did not understand something, then could you answer me why and how?
Conclusion
First...1 First...1 First...1 First...1 First...1 First...2 First...2 First...2 First...2 First...2 Second...1 Second...1 Second...1 Second...1 Second...1 Second...2 Second...2 Second...2 Second...2 Second...2 Expected output
First...1 Second...1 First...1 Second...1 First...1 Second...1 First...1 Second...1 First...1 Second...1 First...2 First...2 First...2 First...2 First...2 Second...2 Second...2 Second...2 Second...2 Second...2