Java Concurrency the synchronized keyword and Lock Interface

Welcome thumbs up reading, learning exchanges together, have questions, please leave a message.
There are also open source on GitHub JavaHouse , star welcome

Quote

When the development process, we encounter concurrency issues. How to deal with it?

One solution, simple and crude: locked. We will give a mighty force pulled over, allowing only one person in single. Literally parallel program is to become a serial program. Reality locks locks, padlocks and drawer, and so on. In Java, we lock that is synchronized keyword and Lock interface.

synchronized keyword

synchronized, also known as synchronization lock, which is a Java keyword. We can guess synchronized principle also JVM virtual machine associated.

synchronized lock object. There is a target called a lock monitor (monitor) things, dependent on the operating system of monitoring lock mutex (Mutex Lock). Operating system switch from user mode thread is actually a kernel mode programming (two states cpu's). The price is a bit high, so synchronized heavyweight behind lock and also the introduction of a biased locking lightweight lock.

Lock (lock surveillance monitor) process analysis ():

  1. When the number is entered into the monitor to 0, thread A
  2. Enter the monitor number is 1
  3. Thread B would like to enter the monitor will be blocked.

A thread can enter the Monitor repeated, it is synchronized reentrant locks, and locks Lock implementation of the same.

  • Program verification
public class SynchronizedTest {
    private static  int i = 0;
    public static void main(String[] args) {
        test();
    }

    public static void test(){
        synchronized (SynchronizedTest.class){
            synchronized (SynchronizedTest.class){
                i++;
            }
        }
    }
}
  • The results run
    the program properly, no error

The method may be modified and synchronized code blocks, the code block is re-entry lock of the above example.

  • Modification methods
public class SynchronizedTest {
    static int n = 100;
    final static CountDownLatch start = new CountDownLatch(n);
    private static  int i = 0;
    public static void main(String[] args) throws InterruptedException {
        for (int j = 0; j < n; j++) {
            Thread thread = new Thread(new addNoSynchronized());
            thread.start();
        }
        start.await();
        System.out.println(i);
    }

    public static class addSynchronized implements Runnable{
        @Override
        public void run() {
            addSynchronized();
        }
        public static synchronized void addSynchronized(){
            for (int j = 0; j < 1000; j++) {
                i++;
            }
            start.countDown();
        }
    }
}
  • operation result
100000

If you remove the synchronized keyword, then run the result is not a high probability 100000, because the thread insecurity.

Lock Interface

Generally, we use the class as a reentrant lock ReentrantLock realize Lock interface.

  • Instructions
public class ReentranLockTest {
    private static int j;
    private static int n = 100;
    private static CountDownLatch latch = new CountDownLatch(n);
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            new Thread(new LockTest()).start();
        }
        latch.await();
        System.out.println("结果为:"+j);
    }

    public static class LockTest implements Runnable{
        static Lock lock = new ReentrantLock();
        @Override
        public void run() {
            lockTest();
            latch.countDown();
        }
        private void lockTest() {
            lock.lock();
            try {
                for (int i = 0; i < 1000; i++) {
                        j++;
                }
            }finally {
                lock.unlock();
            }
        }
    }
}
  • operation result
结果为:100000

Here we locked j ++ this resource area (public resources), lock is a modified static keyword, is a class object, think about what will happen if it is not a class object? That is a chain lock (see Figure).

Chain lock .png

Each thread of the can unlock the lock with a key for the program, lock operation does not make sense. Because we need is a lock.

I welcome attention to the micro-channel public number

No public .jpg

Guess you like

Origin www.cnblogs.com/chenzhuantou/p/11964787.html