synchronized对象级别锁以及类级别锁讲解

synchronized,同步锁,可修饰在对象、方法、代码区,多线程环境下提供同步锁机制,同步的概念就是共享,主要用来对共享资源进行加锁,如果不是共享的资源就没必要加同步锁。

对象级别锁示例:

package com.lzf.thread;

public class MultiThread {

	private  int num;
	private  synchronized void printNum(String str) throws Throwable
	{
		if(str.equals("one"))
		{
			num =100;
			System.out.println("num="+num);
			Thread.sleep(1000);
		}else{
			num = 200;
			System.out.println("num="+num);
		}
		System.out.println("当前线程是"+Thread.currentThread().getName());
	}
	
	public static void main(String[] args) {
		
		final MultiThread m1 = new MultiThread();
		final MultiThread m2 = new MultiThread();
		Thread t1 = new Thread(new Runnable() {
			public void run() {
				try {
					m1.printNum("one");
				} catch (Throwable e) {
					e.printStackTrace();
				}
			}
		},"one");
		
		Thread t2 = new Thread(new Runnable() {
			public void run() {
				try {
					m2.printNum("two");
				} catch (Throwable e) {
					e.printStackTrace();
				}
			}
		},"two");
		
		t1.start();
		t2.start();
	}
}
执行结果如下:

num=200
num=100
当前线程是two
当前线程是one

说明:对象级别的锁是锁定在对象上的一把锁,所有线程在访问该对象时,必须通过竞争来获取执行权,对象与对象之间隔离,没有任何关系。

类级别的锁示例:

package com.lzf.thread;

public class MultiThread {

	private static int num;
	private static synchronized void printNum(String str) throws Throwable
	{
		if(str.equals("one"))
		{
			num =100;
			System.out.println("num="+num);
			Thread.sleep(1000);
		}else{
			num = 200;
			System.out.println("num="+num);
		}
		System.out.println("当前线程是"+Thread.currentThread().getName());
	}
	
	public static void main(String[] args) {
		
		final MultiThread m1 = new MultiThread();
		final MultiThread m2 = new MultiThread();
		Thread t1 = new Thread(new Runnable() {
			public void run() {
				try {
					m1.printNum("one");
				} catch (Throwable e) {
					e.printStackTrace();
				}
			}
		},"one");
		
		Thread t2 = new Thread(new Runnable() {
			public void run() {
				try {
					m2.printNum("two");
				} catch (Throwable e) {
					e.printStackTrace();
				}
			}
		},"two");
		
		t1.start();
		t2.start();
	}
}
执行结果如下:

num=100
当前线程是one
num=200
当前线程是two

说明:给静态方法加上锁就属于类级别加锁,就相当于锁定(XXX.class),处于独占状态,其他线程就处于等待状态,通过竞争去获取执行权。


你可能感兴趣的:(并发编程系列)