[ Java多线程 ] synchronize全局锁和对象锁的区别

对象锁:

/**
 * 全局锁,对象锁的区别
 * @author Z7M-SL7D2
 *
 */

class Person{
	private static int COUNT = 10;
	// 同一时间只允许一个线程吃
	public synchronized void eat() {
			System.out.print("开始吃   ");
			COUNT--;
			System.out.print("  吃东西-" + COUNT);
			System.out.print("   吃完了\n");
	}
}


public class TestAll {
	public static void main(String[] args) {
		Thread thread0 = new Thread(()-> {
			for(int i = 0; i < 3; i++) {
				Person p = new Person();
				p.eat();
			}
				
		});
		
		Thread thread1 = new Thread(()-> {
			for(int i = 0; i < 3; i++) {
				Person p = new Person();
				p.eat();
			}
				
		});
		
		Thread thread2 = new Thread(()-> {
			for(int i = 0; i < 3; i++) {
				Person p = new Person();
				p.eat();
			}
				
		});
		
		thread0.start();
		thread1.start();
		thread2.start();
	}
}

理想状态:


实际结果:出现了多个线程同时吃的情况


以上状态产生的原因是

synchronized对于非静态的同步方法。只是锁住了当前对象的访问权限。意思是使用synchronize同步非静态方法只能锁住一个对象。对于多个对象就没办法了。

要想产生理想的结果有以下两种方法:

1,将方法变为静态方法

2,使用同步代码块同步类(类锁)。

上述两种方法都是使用全局锁的方式。将方法变为静态方法同步的实际上也是将当前类设置为同步锁对对象,称为类锁。

使用方法1,对上述代码Person类的修改:

class Person{
	private static int COUNT = 10;
	// 同一时间只允许一个线程吃
	public static synchronized void eat() {
			System.out.print("开始吃 ");
			COUNT--;
			System.out.print("  吃东西-" + COUNT);
			System.out.print("   吃完了");
			System.out.println();
	}
}

运行结果如下:



使用方法2对上述代码的修改:

class Person{
	private static int COUNT = 10;
	// 同一时间只允许一个线程吃
	public void eat() {
		synchronized (Person.class) {
			System.out.print("开始吃 ");
			COUNT--;
			System.out.print("  吃东西-" + COUNT);
			System.out.print("   吃完了");
			System.out.println();
		}
	}
}

运行结果如下:


上述Person.class就是全局锁。

使用Person person对象作为锁的叫对象锁。











猜你喜欢

转载自blog.csdn.net/bugggget/article/details/80242679