1. Directly on 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 ();//Question 1:lock Why is it defined as finalrandom random = new Random ();p ublic void put (i NT num) {System.out.println (Thread.CurrentThread (). GetName () + ": Before put" +num+ "total:" + total); System.out.println (Thread.CurrentThread (). GetName () + ": After put:" + num + ", total:" + All);} public void get (int. num) {System.out.println (Thread.CurrentThread (). GetName () + ": Before Get" +num+ ", the total is:" + Tota l); total-= num; System.out.println (Thread.CurrentThread (). GetName () + ": After get" + num + ", the total is:" + All ";}} 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 (+), if (num < 0) num =-num;custOmer.lock.lock (); if (customer.total + num <0) {customer.lock.unlock (); try {thread.sleep (+);} catch (Exception e) {/ /TODO auto-generated catch Blocke.printstacktrace ();}} else {try {Thread.Sleep],} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.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 (+), if (num < 0) num =-num;customer.lock.lo CK (); if (Customer.total-num < 0) {customer.lock.unlock (); try {thread.sleep)} catch (Exception e) {//TODO auto-g Enerated catch Blocke.printstacktrace ();}} else {try {Thread.Sleep],} 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 = 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. There is a picture of the truth
Simple deposit and withdrawal implementation in Java multithreading problem