关于java对资源加锁无效的问题

看编程思想一书,也写了段代码,发现对static的资源加锁无效,左思右想终于找出了原因,现贴出与大家分享。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class Source
{
	int i=0;
}
class Generator
{
	public static Integer i=0;
	public static Source source=new Source();
	public static Boolean isCancelled=false;
	public   int next()
	{
		/**
		 * 无效的资源加锁
		 */
		synchronized(i)
		{
		i++;
		Thread.yield();
		i++;
		return i;
		}
		/**
		 * 有效的资源加锁
		 */
//		synchronized(source)
//		{
//			source.i++;
//			Thread.yield();
//			source.i++;
//			return source.i;
//		}
		
	}
	
}
class Increase implements Runnable 
{
	int id;
	Generator gen;
	public Increase(Generator gen,int id)
	{
		this.gen=gen;
		this.id=id;
	}
	@Override
	public void run() {
		while(gen.isCancelled==false)
		{
			int val=gen.next();
			if(val%2!=0)
			{
				gen.isCancelled=true;
				print("#"+id+" error. val="+val);
			}
		}
		print("#"+id+" complete. gen:"+gen.next());
	//	print("#"+id+" complete. gen.i:"+gen.i.);
	}
	public static void print(Object obj)
	{
		System.out.println(obj);
	}
	
}
public class TestLock
{
	static ExecutorService exec = Executors.newCachedThreadPool();
	
	public static void main(String[] args){
		ExecutorService exec = Executors.newCachedThreadPool();
		Generator gen=new Generator();
	    for(int i = 0; i < 10; i++)
	      exec.execute(new Increase(new Generator(), i));
	    exec.shutdown();
		
	}
}

资源加锁的关键是确定所加锁的资源是否是唯一的,是否的分配的唯一内存地址的资源;
上面的无效加锁原因是:static对基本型i 并没有分配内存,而对于封装了的资源source
则用new关键字进行了初始化,并拥有唯一内存,因此对source的加锁才是对单一资源的加锁;
而对于资源i ,10个线程有10个i到底是对谁加锁呢?等于是没有加锁。
(有不恰当处,欢迎吐槽!!!)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值