java中synchronized锁对象的具体理解

1.对于锁参数对象,只有参数对象是同一个对象时才会锁,不同的对象不会锁;

2.锁当前类对象,所有调用该类对象的情况下都会进行锁操作

总结的不好,可能理解不了,直接看代码和执行结果

锁参数对象:
public class TestThread {

	public static void main(String[] args) {
		T2 t2 = new T2();
		new T(t2,"lxl0").start();
		new T(t2,"lxl0").start();
		new T(t2,"lxl2").start();
		new T(t2,"lxl3").start();
	}
}

class T extends Thread {
	T2 t2;
	String userId;

	public T(T2 t2,String userId){
		this.t2 = t2;
		this.userId = userId;
	}
	public void run() {
		t2.m(userId);
	}
}

class T2{
	public void m(String userId) {
		System.out.println("m................");
		synchronized (userId) {
			try {
				System.out.println("userId:" + userId);
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

-----------------------------------------------
执行结果:
m................
userId:lxl0
m................
m................
userId:lxl2
m................
userId:lxl3
userId:lxl0

2.锁类对象

锁类对象:
public class TestThread {

	public static void main(String[] args) {
		T2 t2 = new T2();
		new T(t2,"lxl0").start();
		new T(t2,"lxl0").start();
		new T(t2,"lxl2").start();
		new T(t2,"lxl3").start();
	}
}

class T extends Thread {
	T2 t2;
	String userId;

	public T(T2 t2,String userId){
		this.t2 = t2;
		this.userId = userId;
	}
	public void run() {
		t2.m(userId);
	}
}

class T2{
	public void m(String userId) {
		System.out.println("m................");
		synchronized (this) {
			try {
				System.out.println("userId:" + userId);
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
-----------------------------
执行结果:
m................
userId:lxl0
m................
m................
m................
userId:lxl3
userId:lxl2
userId:lxl0

猜你喜欢

转载自sky-xin.iteye.com/blog/2316923