java multi-threading and thread pool (three): Method unlocked several implementations (2) - synchronized keyword

Yesterday written Lock + Condition of the locking mechanism today to summarize the key points about locks and conditions based on the contents of the book:

Lock for protection code fragment, any time only one thread is executing code in protected.

Lock can manage threads trying to enter the protected code segment.

Lock can have one or more related conditions objects (created using Lock.newCondition)

Each condition object management thread that has entered the protected code segment but does not meet the conditions can not be run.

Today, let us talk about java in an internal lock every object, and if you use a method synchonized keyword statement, then the object's lock will protect the entire method. To call this method, the thread must acquire the object lock within. (Synchronized keyword in the method declaration, you do not need to get locked inside the object, and also without the use of try-finally)

Only one lock internal object related condition, wait method to add a thread to wait set, the waiting thread is released notifyAll blocked state, compared to the conditions for the object, wait () = Condition.await (); notifyAll () = Condition.signalAll ();

Next is the code uses the synchronized keyword:

public class Bank {
    private final double[] accouts;
    private Lock banklock;
    private Condition sufficientFunds;

    public Bank(int n,double initialBalance) {
        accouts = new double[n];
        Arrays.fill(accouts, initialBalance);
        banklock = new ReentrantLock();
        sufficientFunds = banklock.newCondition();
    }

    public synchronized void transfer(int from, int to, double amount) throws InterruptedException{

            while (accouts[from] < amount)
                wait();
            System.out.println(Thread.currentThread());
            accouts[from] -= amount;
            System.out.printf("%10.2f from %d to %d, remain %10.2f", amount, from, to,accouts[from]);
            accouts[to] += amount;
            System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());
            notifyAll();

    }

    public synchronized double getTotalBalance() {
            double sum = 0;
            for (double a : accouts)
                sum += a;

            return sum;
    }

    public int size(){
        return accouts.length;
    }
}

Guess you like

Origin www.cnblogs.com/MYoda/p/11274342.html