Simple implementation of deposit and withdrawal in java Multithreading
1. directly add the Code:
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 (); // problem 1: why is lock defined as finalRandom 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 Customer; public PutMoney (customer 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 blocke. printStackTrace () ;}} else {try {Thread. sleep (100);} catch (InterruptedException e) {// TODO Auto-generated catch blocke. printStackTrace ();} customer. put (num); customer. lock. unlock () ;}}} class GetMoney implements Runnable {Customer 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 blocke. printStackTrace () ;}} else {try {Thread. sleep (100);} catch (InterruptedException e) {// TODO Auto-generated catch blocke. printStackTrace ();} customer. get (num); customer. lock. unlock () ;}}} public class BankTheadDemo {/*** @ param args */public static void main (String [] args) {// TODO Auto-generated method stubCustomer 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. Have a picture and have a truth