同步静态方法

同步静态方法

修饰静态方法,作用于当前类对象加锁,进入同步代码前要获得当前类对象的锁

同步监视器是当前类对象Class c=Date.class

public class App {
	private static int num = 0;

	public static synchronized void add() {
		System.out.println(Thread.currentThread().getName()+":begin...."+new Date());
		int cc = num;
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		cc++;
		num = cc;
		System.out.println(cc);
		System.out.println(Thread.currentThread().getName()+":end...."+new Date());
	}
	public static void main(String[] args)throws Exception {
		Thread[] ts=new Thread[10];
		for(int i=0;i<ts.length;i++) {
			Runnable r=new Runnable() {
				public void run() {
					App app=new App();
					app.add();
				}
			};
			ts[i]=new Thread(r);
			ts[i].start();
		}
		for(Thread temp:ts) {
			temp.join();
		}
		System.out.println("Main:"+num);
	}
}

注意:如果在方法上去掉static,则不能实现锁定效果,因为是对象锁,而在线程中创建了10个对象,各个对象没有任何关系,所以不能达到锁定的效果,但是类锁的效果仍旧有效

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值