java多线程问题中简单的存取款实现
2015-05-19 21:37
507 查看
1.直接上代码:
2.有图有真相
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的多线程实现银行取款的问题
- Java实现 简单的多线程“生产者-消费者”问题
- 多线程经典案例——生产者/消费者问题的Java实现与详解
- 实现了UI的简单群聊(java的IO流和多线程,网络通信)
- JAVA 多线程的简单实现
- JAVA 多线程的简单实现(runnable接口方式)
- 并查集问题:简单java实现
- Java多线程-一个简单的线程,实现挂起和恢复的功能
- Java多线程-一个简单的线程,实现挂起和恢复的功能
- java多线程程序设计一、简单多线程的实现
- java利用lock和unlock实现消费者与生产者问题(多线程)
- 黑马程序员-JAVA学习之用多线程实现简单UDP聊天程序
- java多线程总结六:经典生产者消费者问题实现
- JAVA多线程简单实现方法
- 多线程中的全局信息统计的一种简单实现方式(java实现)
- java设置一段代码执行的超时时间的简单方法 间接实现获取Connection超时问题
- JAVA实现的简单多线程
- JAVA多线程实现读者写者问题
- JAVA多线程实现生产者消费者问题
- Java入门到精通——基础篇之多线程实现简单的PV操作的进程同步