Synchronous static method

Synchronous static method

Modification of static methods, acting on the lock of the current class object, and obtaining the lock of the current class object before entering the synchronization code

The synchronization monitor is the current class object Class c=Date.class

public class App {
	private static int num = 0;

	public static synchronized void add() {
		System.out.println(Thread.currentThread().getName()+":begin...."+new Date());
		int cc = num;
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		cc++;
		num = cc;
		System.out.println(cc);
		System.out.println(Thread.currentThread().getName()+":end...."+new Date());
	}
	public static void main(String[] args)throws Exception {
		Thread[] ts=new Thread[10];
		for(int i=0;i<ts.length;i++) {
			Runnable r=new Runnable() {
				public void run() {
					App app=new App();
					app.add();
				}
			};
			ts[i]=new Thread(r);
			ts[i].start();
		}
		for(Thread temp:ts) {
			temp.join();
		}
		System.out.println("Main:"+num);
	}
}

Note : If you remove static on the method, the locking effect cannot be achieved. Because it is an object lock, and 10 objects are created in the thread, each object has no relationship, so the locking effect cannot be achieved, but the effect of the class lock is still valid

Guess you like

Origin blog.csdn.net/qq_45874107/article/details/113876422
Recommended