Java Concurrent synchronized keyword and lock interface

Time:2019-12-28

Java Concurrent synchronized keyword and lock interface

Welcome to like reading, study and exchange together, please leave a message if you have any questions.
Open source javahouse is also available on GitHub. Welcome to star

Quote

During the development process, we encountered concurrency problems. How to solve it?

One solution, simple and crude: lock. Stop thousands of troops and horses. Only one person is allowed to cross the bridge. Written means to change a parallel program into a serial program. There are locks, padlocks, drawer locks and so on. In Java, our lock is the synchronized keyword and lock interface.

Synchronized keyword

Synchronized, also known as synchronization lock, is a key word in Java. We can guess that the synchronized principle is also related to the JVM virtual machine.

Synchronized locks are objects. There is a thing called monitor in the object, which depends on mutex lock of the operating system. Operating system switching thread is actually from the user state programming kernel mentality (two states of CPU). The cost is a little high, so biased lock and lightweight lock are introduced after synchronized.

Analysis of lock adding (monitoring lock monitor) process ():

  1. When the number of monitor entries is 0, thread a enters
  2. Monitor has 1 entries
  3. Thread B will be blocked if it wants to enter the monitor.

Thread a can repeatedly enter the monitor, so synchronized is a reentrant lock, just like the lock implemented by lock.

  • 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++;
            }
        }
    }
}
  • Operation result

The program runs normally without error

Synchronized can modify methods and code blocks, which are examples of the above reentry locks.

  • Modification method
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 the synchronized keyword is removed, the running result rate is probably not 100000 because of thread insecurity.

Lock interface

In general, we use reentrantlock class as reentrant lock to implement lock interface.

  • Usage method
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 ("result is:" + 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
Result: 100000

Here we lock the j + + resource area (public resource). The lock is decorated by the static keyword and is a class object. What if it is not a class object? That’s chain lock.

Java Concurrent synchronized keyword and lock interface

Each thread can unlock the lock with the key. For the program, the lock operation is meaningless. Because what we need is a lock.

Welcome to my WeChat public address.

Java Concurrent synchronized keyword and lock interface

Recommended Today

How to connect Oracle database with PL / SQL developer

Before because of the project, Oracle database was needed. Because of the limited time, it was impossible to learn from the foundation, and the command interface of Oracle operation was too unfriendly, so we found PL / SQL developer, a very useful software, to indirectly use the database. Here is a brief introduction of how […]