在其他对象上同步

      synchronized块必须给定一个在其上进行同步的对象,最合理的方式是:使用其方法正在被调用的当前方法:synchronized(this)。

      但是有的时候必须在另一个对象上同步。

      我们看两个代码的例子:

                                                                                 1.

package com.wjy.test;


public class Dualsynch{
	private Object myObject=new Object();
	public synchronized void f(){
		for(int i=0;i<10;i++){
			System.out.println("I am f function.");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	public void g(){
		synchronized (this) {
			for(int i=0;i<10;i++){
				System.out.println("I am g function.");
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}

 测试代码:

 

 

package com.wjy.test;

public class TestMain {
	public static void main(String args[]) {
		final Dualsynch dualsynch=new Dualsynch();
		new Thread(){
			public void run(){
				dualsynch.f();
			}
		}.start();
		
		dualsynch.g();
	}
}

 运行结果:

 

I am g function.
I am g function.
I am g function.
I am g function.
I am g function.
I am g function.
I am g function.
I am g function.
I am g function.
I am g function.
I am f function.
I am f function.
I am f function.
I am f function.
I am f function.
I am f function.
I am f function.
I am f function.
I am f function.
I am f function.

 很明显,进程发生了阻塞。但是修改代码synchronized(this)中的this后,救国救民不同了,因为两个函数(f 和  g)是在不同对象上同步的。

                                                                     2

package com.wjy.test;


public class Dualsynch{
	private Object myObject=new Object();
	public synchronized void f(){
		for(int i=0;i<10;i++){
			System.out.println("I am f function.");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	public void g(){
		synchronized (myObject) {
			for(int i=0;i<10;i++){
				System.out.println("I am g function.");
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}

 测试代码没有变,看看结果:

I am g function.
I am f function.
I am f function.
I am g function.
I am f function.
I am g function.
I am g function.
I am f function.
I am f function.
I am g function.
I am g function.
I am f function.
I am g function.
I am f function.
I am g function.
I am f function.
I am f function.
I am g function.
I am f function.
I am g function.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值