001    
002    /**
003     * Konto version B.
004     * Uses synchronized methods to display, add and remove money 
005     * from the account, account cannot become negative.
006     * @author Heinz Kredel.
007     */ 
008    public class KontoB implements Konto {
009    
010        private double stand; // Konto Stand
011    
012        public KontoB() { stand = 0.0; } // sets Kontostand to desired value
013    
014        public KontoB(double a) { stand = a; }
015        
016    /**
017     * Displays account balance.
018     * @return stand.
019     */
020            public synchronized double zeigeGeld() { return stand; }
021    
022    /**
023     * Transfers amount to this account.
024     * Blocks if account would become negative.
025     * @param b amount to put on account.
026     * @return s returns actual balance from account.
027     */
028        public synchronized double putGeld(double b) { // stand += b
029            double s = stand + b;
030            WorkB.schaffen(100);
031            // nur falls s >= 0
032            while (s < 0 && stand > s) {
033                    try { 
034                        this.wait();       
035                    } catch(InterruptedException e) { } 
036                    s = stand + b;
037            }
038            if (s >= 0 || s > stand) this.notify();
039            stand = s;
040            return s;   
041        }
042    
043        
044    /**
045     * New account balance gets calculated and returned.
046     * Blocks if account would become negative.
047     * @param b amount to remove from desired account.
048     * @return s current account balance.
049     */
050        public synchronized double getGeld(double b) { // stand -= b
051            double s = stand - b;
052            WorkB.schaffen(100);
053            // nur falls s >= 0
054            while (s < 0 && stand > s) {
055                    try { 
056                        this.wait();       
057                    } catch(InterruptedException e) { } 
058                    s = stand - b;
059            }
060            if (s >= 0 || s > stand) this.notify();
061            stand = s;
062            return s;   
063        }
064    
065    }
066    
067    
068    /**
069     * sending current thread to sleep for a random time.
070     */
071    class WorkB {
072    
073    /**
074     * @param max defines range of numbers for Math.random().
075     */
076        public static void schaffen(int max) {
077            try {
078                Thread.currentThread().sleep( (int)(max*Math.random()) );
079            } catch (InterruptedException e) {
080                  System.out.println("Dies sollte nicht passieren "+e);
081            }
082        }
083    }