static method plus lock, and non-static method lock Difference

Source: Internet
Author: User
Tags instance method

Today, I saw the interesting question: what is the difference between locking and non-static methods on static methods, so that some understanding of the lock mechanism is introduced again.

First look at the method:

This is a very simple class that shares static variable num, and then a static and non-static method, all with a lock

We assume that there are two threads that operate both methods simultaneously, so can data be mutually exclusive?

Java code
  1. Public class Walk {
  2. public static int num = 100;
  3. public static Walk Walk = new Walk ();
  4. //Static
  5. public synchronized static int run () {
  6. int i = 0;
  7. While (I < ) {
  8. try {
  9. Num--;
  10. i++;
  11. System.out.println (Thread.CurrentThread (). GetName () +":" +num);
  12. Thread.Sleep (1000);
  13. } catch (Interruptedexception e) {
  14. E.printstacktrace ();
  15. }
  16. }
  17. return num;
  18. }
  19. //non-static
  20. public synchronized int Walk () {
  21. int i = 0;
  22. While (I < ) {
  23. try {
  24. Num--;
  25. i++;
  26. System.out.println (Thread.CurrentThread (). GetName () +":" +num);
  27. Thread.Sleep (1000);
  28. } catch (Interruptedexception e) {
  29. E.printstacktrace ();
  30. }
  31. }
  32. return num;
  33. }
  34. }
  35. First set up two test classes, here we loop 10 times by default
  36. Public class T3 implements Runnable {
  37. @Override
  38. public Void Run () {
  39. Walk Walk = new Walk ();
  40. //walk Walk = Walk.walk;
  41. Walk.walk ();
  42. }
  43. }
  44. Public class T1 implements runnable{
  45. @Override
  46. public Void Run () {
  47. Walk Walk = new Walk ();
  48. //walk Walk = Walk.walk;
  49. //Here I still use the new
  50. Walk.run ();
  51. }
  52. }

Java code
  1. Test method
  2. Public class Test {
  3. public static void Main (string[] args) {
  4. Thread T1 = new Thread (new T1 ());
  5. thread t3 = new Thread (new T3 ());
  6. Executorservice es = Executors.newcachedthreadpool ();
  7. Es.execute (t1);
  8. Es.execute (T3);
  9. Es.shutdown ();
  10. }
  11. }

Test data I'm not completely listed.

Pool-1-thread-1:98

Pool-1-thread-2:98

pool-1-thread-2:97

pool-1-thread-1:96

.....

You can see that two threads are not mutually exclusive, which is why?

OK, we will remove the static keyword, the code I will not post, directly see the results.

Pool-1-thread-1:98

Pool-1-thread-2:98

pool-1-thread-2:96

...

The result is that there is no mutex, so we have to let a thread execute 10 times by default, assuming that this is the ticket system which is not allowed. Why this happens, the method is added to the lock.

First, the understanding of the lock is introduced, and then explained from the back forward.

JAVA's lock mechanism description: Each object has a lock and is unique. Suppose an object space is allocated, there are several methods, the equivalent of space inside a number of small rooms, if we lock all the small rooms, because this object has only one key, so at the same time only one person can open a small room, and then use it back, and then by the JVM to assign the next person to get the key.

In the second experiment, we locked the method, but didn't get the result we wanted because of the room and the key. Because each of our threads is a new object when invoking the method, there are two spaces, two keys, and only one static variable, which is equivalent to having two keys, opening a shared value from a different room, and therefore making an error.

What if we use static variable walk? This code release, that is, we use an object to manipulate the variable, then the result:

Use Walk.walk.walk (); and Walk.run ();

Result: There is still no mutex

pool-1-thread-1:99

Pool-1-thread-2:98

pool-1-thread-1:97

...

If we remove the static method keyword: We can see the mutex.

pool-1-thread-1:99

Pool-1-thread-1:98

pool-1-thread-1:96

The results are still repeated, so we can draw a lock on the static method and lock it on the normal method, they are not using the same place, not the same key. So that their object locks are different and objects are different.

Here again, a concept: object locks and Class locks

Object Lock: When the JVM creates the object, the default is to give each object a unique object lock, a key

Class Locks: Each class is an object, and each object has an object lock.

Hehe, the concept of confusion, in fact, are locked, take two nouns, the following easy to distinguish, the effect is the same, if we achieve this.

Java code
  1. Static, this simply turns the method into a class lock.
  2. public static int run () {
  3. synchronized (Walk. Class) {
  4. int i = 0;
  5. While (I < ) {
  6. try {
  7. Num--;
  8. i++;
  9. System.out.println (Thread.CurrentThread (). GetName () +":" +num);
  10. Thread.Sleep (1000);
  11. } catch (Interruptedexception e) {
  12. E.printstacktrace ();
  13. }
  14. }
  15. return num;
  16. }
  17. }

Results:

Pool-1-thread-1:98

Pool-1-thread-2:98

pool-1-thread-2:97

pool-1-thread-1:97

...

The result is not mutually exclusive, indicating that the lock on the static method, and the instance method lock, object lock is actually not the same. If we change to:

Synchronized (walk) {

//.... Slightly

}

Results:

pool-1-thread-2:99

Pool-1-thread-2:98

pool-1-thread-2:97

This is mutually exclusive, because T1 is called by the static variable walk, the default is to use the Walk object this lock, and static method force let him also use walk this lock, there is a mutual exclusion phenomenon, because the key only one.

What if all two of our methods are static methods?

..

Summary:

1. Object lock key Only one can be mutually exclusive, in order to guarantee the uniqueness of shared variables

2. In the static method of the lock, and the instance method on the lock, the default is not the same, if the synchronization needs to make two locks.

3. The lock on a method of the same class comes from the object that called the method, and if the object calling the method is the same, then the lock must be the same, otherwise it will be different. For example, new A (). x () and new A (). x (), the object is different, the lock is different, if a's simple interest, it can be mutually exclusive.

4. Static method lock, can be locked with all other static methods of mutual exclusion

5. Static method lock, and Xx.class lock effect, directly belongs to the class

Static method lock, and non-static method lock difference

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.