码迷,mamicode.com
首页 > 编程语言 > 详细

java多线程问题中简单的存取款实现

时间:2015-05-19 22:40:58      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:reentrantlock

1.直接上代码:

package com.mnmlist.java.grammar;

import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

class Customer {
	int total;
	public Customer() {
		total = 0;
	}

	public final ReentrantLock lock = new ReentrantLock();// 问题1:lock为什么定义为final
	Random random = new Random();
	public void put(int num) {

		System.out.println(Thread.currentThread().getName()+":before put "+num+" ,total:" + total);
		total += num;
		System.out.println(Thread.currentThread().getName()+":after put:" + num + ",total:" + total);

	}

	public void get(int num) {
		System.out.println(Thread.currentThread().getName()+":before get "+num+" ,the total is:" + total);
		total -= num;
		System.out.println(Thread.currentThread().getName()+":after get " + num + " ,the total is:" + total);
	}
}

class PutMoney implements Runnable {
	Customer customer;

	public PutMoney(Customer customer) {
		this.customer = customer;
	}

	public void run() {
		int num = 0;
		while (true) {
			num = customer.random.nextInt(100);
			if (num < 0)
				num = -num;
			customer.lock.lock();
			if (customer.total + num <0) {
				customer.lock.unlock();
				try {
					Thread.sleep(100);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				customer.put(num);
				customer.lock.unlock();
			}
		}
	}

}

class GetMoney implements Runnable {
	Customer customer;

	public GetMoney(Customer customer) {
		this.customer = customer;
	}

	public void run() {
		int num = 0;
		while (true) {
			num = customer.random.nextInt(100);
			if (num < 0)
				num = -num;
			customer.lock.lock();
			if (customer.total - num < 0) {
				customer.lock.unlock();
				try {
					Thread.sleep(100);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				customer.get(num);
				customer.lock.unlock();
			}
		}
	}
}

public class BankTheadDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Customer customer = new Customer();
		PutMoney putMoney = new PutMoney(customer);
		GetMoney getMoney = new GetMoney(customer);
		Thread t1 = new Thread(putMoney);
		Thread t2 = new Thread(getMoney);
		t2.start();
		t1.start();
		
	}

}

2.有图有真相

技术分享


java多线程问题中简单的存取款实现

标签:reentrantlock

原文地址:http://blog.csdn.net/mnmlist/article/details/45850269

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!