java concurrent synchronization

synchronized keyword usage in java

We can add keyword "synchronized" at the beginning of function to lock the function when we call this function.

If the function is a non-static member of a class, the lock scope  is object-wide

if the function is a static member of a class , the lock scope is class-wide.

example1:for static member

public class Test { synchronized public static void test_object() throws InterruptedException { while(true){ System.out.println("test object"); TimeUnit.MILLISECONDS.sleep(1000); } } //synchronized synchronized public static void test_static() throws InterruptedException { while(true) { System.out.println("test static"); TimeUnit.MILLISECONDS.sleep(1000); } } }


two static functions : test_object, test_static. if one object or class access to the function test_object, other object or class cannot access to the function test_static.


example2:for non-static member
class SyncTest { synchronized public void test_object() throws InterruptedException { while(true){ System.out.println("test object"); TimeUnit.MILLISECONDS.sleep(1000); } } //synchronized synchronized public void test_static() throws InterruptedException { while(true) { System.out.println("test static"); TimeUnit.MILLISECONDS.sleep(1000); } } }

two non-static member functions: the same object cannot call test_object and test_static both.

example3:one non-static member and one static member
class SyncTest { synchronized public void test_object() throws InterruptedException { while(true){ System.out.println("test object"); TimeUnit.MILLISECONDS.sleep(1000); } } //synchronized synchronized public static void test_static() throws InterruptedException { while(true) { System.out.println("test static"); TimeUnit.MILLISECONDS.sleep(1000); } } }

if a object call test_object and concurrently it can call test_static. equally if a object call test_static it can also call test_object at the same time.

summary: synchronized keyword can add a lock to a object if the called function is a non-static function, or a class if the called function is static function.

你可能感兴趣的:(java concurrent synchronization)