2015.11.1

线程关键字:synchronized;作用:同步锁,使得线程有先后顺序。

 
public class Test {
   public static void main(String[] args){
	   Account account = new Account(1000);
	   
      OperationThread oper1 = new OperationThread(account,500,"柜台");
      OperationThread oper2 = new OperationThread(account,600,"ATM");
      oper1.start();
      oper2.start();
   }
}

public class  Account {

	private int count;
	public Account(int count){
		this.count = count;
	}
	public int getCount(){
		return count;
	}
	public synchronized int getCash(int cash){
		if(cash>count){
			return -1;
		}else if(cash<count){
			count = count-cash;
		}	
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
	
		}
		
		return cash;
	}
}

public class OperationThread extends Thread{
   private  Account account;
   private int cash;
   private String OperationType;
   public OperationThread(Account account,int cash,String OperationType){
	   this.account=account;
	   this.cash=cash;
	   this.OperationType=OperationType;
   }
   public void run(){
	   super.run();
	   int result = account.getCash(cash);
	   if(result==-1){
		   System.out.println(OperationType+"取现失败,账户余额为:"+account.getCount()+",准备取现的额度为:"+cash);
		}else{
			System.out.println(OperationType+"取现成功,账户余额为:"+account.getCount()+",准备取现的额度为:"+cash);
	   }
   }
}


输出的结果:

ATM取现失败,账户余额为:500,准备取现的额度为:600
柜台取现成功,账户余额为:500,准备取现的额度为:500


线程池;多个线程的存在,但是过多的线程严重消耗cpu,因此,

线程池里的每个线程需要重复利用,意味着建立线程池:

 

public static void main(String[] args) {
	
		ThreadPool pool = new ThreadPool();
		
		for(int i=0;i<60;i++){
			MyTask task = new MyTask(i);
			pool.excute(task);
		}

run方法:

public void run() {
		while(true){
			//同步关键字
			synchronized (taskList) {
				if(taskList.isEmpty()){
					try {
						taskList.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
			//取出一个任务,并执行
			MyTask task = taskList.remove(0);
			System.out.println(this.getName()+"开始执行"+task.index+"任务");
			task.work();
		}
	}








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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值