Java static synchronization method and non static synchronization method

Question 1: whether static and non static methods have competition state ...
Question 1: whether static and non static methods have competition state
Problem 2: there is no race condition between synchronized (this.getClass()) and static synchronization method
summary

Question 1: whether static and non static methods have competition state

Static synchronization method and non-static synchronization method have no competition condition. Generally speaking, the two threads that call static synchronization method and non-static synchronization method respectively will synchronize?

No, the static method requests the synchronization monitor of the class, and the non static method requests the monitor of the instance.

Here is the test code:

public class TestSynchronized { static final int COUNT = 1000; static synchronized void staticSyn() { for (int i = 0; i < COUNT; i++) { System.out.println("staticSyn " + i); } } synchronized void instanceSyn() { for (int i = 0; i < COUNT; i++) { System.out.println("instanceSyn " + i); } } void blockInstance() { synchronized (this) { for (int i = 0; i < COUNT; i++) { System.out.println("blockInstance " + i); } } } void blockClass() { synchronized (this.getClass()) { for (int i = 0; i < COUNT; i++) { System.out.println("blockClass " + i); } } } }

Test:

public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { TestSynchronized.staticSyn(); } }).start(); new Thread(new Runnable() { @Override public void run() { new TestSynchronized().instanceSyn(); } }).start(); }

Partial output:

staticSyn 953 staticSyn 954 staticSyn 955 staticSyn 956 staticSyn 957 staticSyn 958 staticSyn 959 instanceSyn 671 instanceSyn 672 instanceSyn 673 instanceSyn 674 staticSyn 960 staticSyn 961 staticSyn 962 staticSyn 963

Problem 2: there is no race condition between synchronized (this.getClass()) and static synchronization method

Yes, both are synchronization monitors for request classes.

Test code:

public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { TestSynchronized.staticSyn(); } }).start(); new Thread(new Runnable() { @Override public void run() { new TestSynchronized().blockClass(); } }).start(); }

Output results:

staticSyn 994 staticSyn 995 staticSyn 996 staticSyn 997 staticSyn 998 staticSyn 999 blockClass 0 blockClass 1 blockClass 2 blockClass 3 blockClass 4 blockClass 5 blockClass 6 blockClass 7 blockClass 8

summary

1. There is no competition condition between static synchronization method and non static synchronization method;
2. synchronized (this.getClass()) and static synchronization methods have race conditions, both of which request the synchronization monitor of the class.

4 May 2020, 20:36 | Views: 5302

Add new comment

For adding a comment, please log in
or create account

0 comments