synchronized scope of action
- Decorated code block: decorated scope is the code surrounded by braces, which acts on the called object
- Decorated method: the decorated scope is the whole method, which acts on the calling object
- Decorate static method: the scope of decoration is the whole static method, which acts on all objects
- Modifier class: the modifier scope is the bracketed part, which acts on all objects
public class SynchronizedBlock { public void test(String threadName){ synchronized (this){ for (int i=0;i<10;i++){ System.out.println("test--:"+threadName+" "+i); } } } public synchronized void test2(){ for (int i=0;i<10;i++){ System.out.println("test2-i:"+i); } } public static void main(String[] args) { final SynchronizedBlock syn1 = new SynchronizedBlock(); final ExecutorService executorService = Executors.newCachedThreadPool(); executorService.execute(new Runnable() { @Override public void run() { syn1.test(Thread.currentThread().getName()); } }); executorService.execute(new Runnable() { @Override public void run() { syn1.test(Thread.currentThread().getName()); } }); } }
The above code runs as expected, and the two threads output 0-9 in sequence
public static void main(String[] args) { final SynchronizedBlock syn1 = new SynchronizedBlock(); final SynchronizedBlock syn2 = new SynchronizedBlock(); final ExecutorService executorService = Executors.newCachedThreadPool(); executorService.execute(new Runnable() { @Override public void run() { syn1.test(Thread.currentThread().getName()); } }); executorService.execute(new Runnable() { @Override public void run() { syn2.test(Thread.currentThread().getName()); } }); }
If there were two instances, what would the result be?
Multiple runs result in different results. It can be seen that when synchronized modifies code blocks and non static methods, the objects that are locked are only the current calling objects.
public class SynchronizedBlock { public void test(String threadName){ synchronized (SynchronizedBlock.class){ for (int i=0;i<10;i++){ System.out.println("test--:"+threadName+" "+i); } } } public synchronized static void test2(String threadName){ for (int i=0;i<10;i++){ System.out.println("test2--:"+threadName+" "+i); } } public static void main(String[] args) { final SynchronizedBlock syn1 = new SynchronizedBlock(); final SynchronizedBlock syn2 = new SynchronizedBlock(); final ExecutorService executorService = Executors.newCachedThreadPool(); executorService.execute(new Runnable() { @Override public void run() { syn1.test2(Thread.currentThread().getName()); } }); executorService.execute(new Runnable() { @Override public void run() { syn2.test2(Thread.currentThread().getName()); } }); } }
When synchronized modifies a class and a static method, the locked object is all instances of that class.