Java synchronized一个实例_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Java synchronized一个实例

Java synchronized一个实例

 2013/10/25 18:46:03  alleni123  程序员俱乐部  我要评论(0)
  • 摘要:packagecom.lj.thread7;publicclassFetchMoney{publicstaticvoidmain(String[]args){Bankbank=newBank();Threadt1=newThread(newMoneyThread(bank),"t1");Threadt2=newThread(newMoneyThread(bank),"t2");t1.start();t2.start();//System.out.println(bank.getMoney())
  • 标签:Java 一个 Ron 实例
class="java">package com.lj.thread7;

public class FetchMoney
{
	public static void main(String[] args)
	{	
		Bank bank=new Bank();
		Thread t1=new Thread(new MoneyThread(bank),"t1");
		Thread t2=new Thread(new MoneyThread(bank),"t2");
		
	
	 
		t1.start();
		t2.start(); 
		
		//System.out.println(bank.getMoney());
		
		
	}
}


class Bank{
	private static Integer money=1000;
	
	public int getMoney(){
		return this.money;
	}
	
	public void changeMoney(int number) throws InterruptedException{
		
		[b]synchronized [/b](money)
		{
			Thread.sleep(5000);
			money+=number;
		}
		
		
		
		System.out.println("money= "+money);
		
	}
	
	public [b]synchronized [/b]int  getMoney(int number) throws InterruptedException{
		
		if(number<0){
			return -1;
		}
		else if(number >money){
			return -2;
		}
		else{
			
			//模拟一下取款所用的时间
			Thread.sleep(3000);
			
			money-=number;
			
			System.out.println("money= "+money+" by "+Thread.currentThread().getName());
			return number;
		
		}
	}
}


class MoneyThread implements Runnable{
	
	private Bank bank;
	
	
	
	
	public MoneyThread(Bank bank)
	{
		this.bank = bank;
	}




	@Override
	public void run()
	{
		try
		{
			//System.out.println(bank.getMoney(800));
			bank.changeMoney(500);
		}
		catch (InterruptedException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
}


这里分别用synchronized锁定了方法和变量对象。
两种方法都可以实现对对象的锁定, 然后让不同的线程有先后顺序的访问。



//等待编辑
发表评论
用户名: 匿名