Synchronized keywords are the following 3 ways to apply the main
A modified instance method, which is used to lock the current instance, to obtain the lock of the current instance before entering the synchronization code; Instance lock, one instance lock
Modify the static method, for the current class object lock, before entering the synchronization code to obtain the current class object lock; object lock, one object lock
Modifies the code block, specifies the lock object, locks the given object, and obtains the lock of the given object before entering the synchronization code base; object lock, one object lock
Instance lock public class Superhakcetest implements runnable{public static Integer flag = 0; Public synchronized void Instanse () {flag + +; } @Override public void Run () {for (int i = 0;i < 1000;i + +) {instanse (); }} public static void Main (string[] args) throws exception{superhakcetest superhakcetest = new Superhakcete St (); Thread thread1 = new Thread (superhakcetest); Thread thread2 = new Thread (superhakcetest); Thread thread3 = new Thread (superhakcetest); Thread1.start (); Thread2.start (); Thread3.start (); Thread1.join (); Thread2.join (); Thread3.join (); System.out.println ("Last FLAG =" + Superhakcetest.flag); }} object lock public class Superhakcetest implements runnable{public static Integer flag = 0; public static synchronized void Instanse () {flag + +; } @Override public void Run () {for (int i = 0;i < 1000;i + +) {instanse (); }} public Static void Main (string[] args) throws exception{superhakcetest superHakceTest1 = new Superhakcetest (); Superhakcetest superHakceTest2 = new Superhakcetest (); Superhakcetest superHakceTest3 = new Superhakcetest (); Thread thread1 = new Thread (SUPERHAKCETEST1); Thread thread2 = new Thread (SUPERHAKCETEST2); Thread thread3 = new Thread (SUPERHAKCETEST3); Thread1.start (); Thread2.start (); Thread3.start (); Thread1.join (); Thread2.join (); Thread3.join (); System.out.println ("Last FLAG =" + Superhakcetest.flag); }}//this, the current instance object lock synchronized (this) {for (int j=0;j<1000000;j++) {i++; }}//class Object lock synchronized (Accountingsync.class) {for (int j=0;j<1000000;j++) {i++; }}
Java concurrency synchronized