Method Lock, Object Lock, Class Lock

Keywords: Programming Windows

Method lock:

Method lock is a kind of object lock:

Code: Four windows to sell tickets. Each window sells four, one window sells out and the next one sells.

/**
 * Object Lock, Square Lock, Class Lock
 * 
 * @author my
 *
 */
public class ObjectLock {
	public synchronized void sellTickets() { //Square locks, a kind of object locks
		int n = 4;
		while(n>0) {
			System.out.println(Thread.currentThread().getName() + " Votes" + n);
			n--;
			
		}
		
	}

public static void main(String[] args) {
	ObjectLock ol = new ObjectLock();
	Thread t1 = new Thread(new Runnable() {

		@Override
		public void run() {
			ol.sellTickets();
			
		}
		
	});
	Thread t2  = new Thread(new Runnable() {

		@Override
		public void run() {
			ol.sellTickets();
			
		}
		
	});
	Thread t3 = new Thread(new Runnable() {

		@Override
		public void run() {
			ol.sellTickets();
			
		}
		
	});
	Thread t4  = new Thread(new Runnable() {

		@Override
		public void run() {
			ol.sellTickets();
			
		}
		
	});
	
	t1.start();
	t2.start();
	t3.start();
	t4.start();
}

}

Object lock

public  void sellTickets() { //public synchronized void sellTickets() method lock, a kind of object lock
		synchronized(this) { //synchronized(this) object lock, four threads are accessed by the same object, so locked
			int n = 4;
			while(n>0) {
				System.out.println(Thread.currentThread().getName() + " Votes" + n+" Current object lock this For:"+this);
				n--;
				
			}
		}
		
	}

Testing different objects: obviously, this is not locked

/*
	 * Different object ol2 to test object locks
	 */
	ObjectLock ol2 = new ObjectLock();
	Thread different = new Thread(new Runnable() {

		@Override
		public void run() {
			ol2.sellTickets();
			
		}
		
	},"different object");
	different.start();

Class lock:

Locked like different objects
In fact, class lock is only a conceptual thing, not a real thing, it is used to help us understand the difference between lock instance method and static method.

Code block mode:

public  void sellTickets() { 
	synchronized(ObjectLock.class) { //Class Locks, Locked Like Different Objects
		int n = 4;
		while(n>0) {
			System.out.println(Thread.currentThread().getName() + " Votes" + n+" Current object lock this For:"+this);
			n--;
			
		}
	}

Modification methods:

public static synchronized void add(int m){  
    String name = Thread.currentThread().getName();  

    System.out.println("Class lock");   
}

Posted by gewthen on Fri, 01 Feb 2019 21:42:16 -0800