java synchronized详解

Java语言的关键字,当它用来修饰一个方法或者一个代码块的时候,可以保证在同一时刻最多只有一个线程执行该段代码。 1、当两个并发线程访问同一个对象object中的这个synchronized(this)同步代码块时,一个时间内只能有一个线程获得执行。另外一个线程必须等待当前线程执行完这个代码块之后才能执行该代码块。 2、然而,当一个线程访问object的一个synchronized(this)同步代码块时,另外一个线程仍然能够访问该object中的非synchronized(this)同步代码块。 3、尤为关键的是,当一个线程访问object的一个synchronized(this)同步代码块时,其余线程对object中全部其它synchronized(this)同步代码块的访问将被阻塞。 4、第三个例子一样适用其它同步代码块。也就是说,当一个线程访问object的一个synchronized(this)同步代码块时,它就得到了这个object的对象锁。结果,其它线程对该object对象全部同步代码部分的访问都被暂时阻塞。 5、以上规则对其它对象锁一样适用.并发

例1:当两个并发线程访问同一个对象object中的这个synchronized(this)同步代码块时,一个时间内只能有一个线程获得执行。另外一个线程必须等待当前线程执行完这个代码块之后才能执行该代码块。 public class Test implements Runnable{ public void run() {
// synchronized(this) { //线程阻塞 for (int i = 0; i < 5000; i++) {
System.out.println(Thread.currentThread().getName() + " synchronized loop " + i);
}
}
// }
public static void main(String[] args) {
Test t1 = new Test();
Thread ta = new Thread(t1, "A"); //建立一个线程A Thread tb = new Thread(t1, "B"); //建立一个线程B ta.start();
tb.start();
} }oop

例二:当一个线程访问object的一个synchronized(this)同步代码块时,另外一个线程仍然能够访问该object中的非synchronized(this)同步代码块。this

public class Test1 {线程

public void m4t1() {
	synchronized (this) {
		int i = 5;
		while (i-- > 0) {
			System.out.println(Thread.currentThread().getName() + " : " + i);

			try {
				Thread.sleep(500);// 睡眠半秒
			} catch (InterruptedException ie) {

			}
		}
	}
}

public void m4t2() {
	int i = 5;
	while (i-- > 0) {
		System.out.println(Thread.currentThread().getName() + " : " + i);
		try {
			Thread.sleep(500);// 睡眠半秒
		} catch (InterruptedException ie) {

		}
	}
}

public static void main(String[] args) {
	final Test1 myt2 = new Test1();
	Thread t1 = new Thread(new Runnable() {
		public void run() {
			myt2.m4t1();
		}
	}, "t1");
	Thread t2 = new Thread(new Runnable() {
		public void run() {
			myt2.m4t2();
		}
	}, "t2");
	t1.start();
	t2.start();
}

}code

例三:当一个线程访问object的一个synchronized(this)同步代码块时,其余线程对object中全部其它synchronized(this)同步代码块的访问将被阻塞。 //修改Test1.m4t2()方法:
public void m4t2() {
synchronized(this) {
int i = 5;
while( i-- > 0) {
System.out.println(Thread.currentThread().getName() + " : " + i);
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
}
}
} }对象

例四:当一个线程访问object的一个synchronized(this)同步代码块时,它就得到了这个object的对象锁。结果,其它线程对该object对象全部同步代码部分的访问都被暂时阻塞。 //修改Thread2.m4t2()方法:
public void m4t2() {
synchronized(this) {
int i = 5;
while( i-- > 0) {
System.out.println(Thread.currentThread().getName() + " : " + i);
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
}
}
} }接口

例五:以上规则对其它对象锁一样适用:(项目中使用过,更新玩家等级数据接口,定义一个对象,给它加锁)get

private void m4t1(Inner inner) { synchronized(inner) { //使用对象锁 inner.m4t1(); }同步

相关文章
相关标签/搜索