java multithreading-synchronous lock-implicit lock-display lock

java multithreading-synchronous lock-implicit lock-display lock

Northwest Wild Wolf
My github: https://github.com/soyoungboy
My segmentfault: http://segmentfault.com/u/soyoungboy

[If you don t accumulate steps, you can t reach a thousand miles; if you don t accumulate small streams, you can t make a river]
Blog Garden   Homepage   New Essay   Contact   Subscription   management Essay-477 Comments-20 Article-0 

java multithreading-synchronization lock

In order to solve the multi-threaded safety problem
before Java 5.0, the only mechanisms that can be used when coordinating the access of shared objects are synchronized and volatile.
Some new mechanisms have been added after Java 5.0, but they are not a way to replace the built-in lock, but as an optional advanced feature when the built-in lock is not applicable.

Implicit lock

synchronized

  1. Synchronization code block;
  2. Synchronization method.

Display lock Lock

After jdk 1.5: Synchronous lock Lock needs to be locked through the lock() method, and the lock must be released through the unlock() method. ReentrantLock implements the Lock interface and provides the same mutual exclusion and memory visibility as synchronized. But compared to synchronized, it provides higher flexibility in handling locks.

How to use Lock:

Lock lock = new ReentrantLock();
lock.lock();
try {
} finally {
lock.unlock();
} 

Related API:

  1. void lock() Acquire the lock.
  2. void lockInterruptibly() If the current thread is not interrupted, acquire the lock.
  3. Condition newCondition() Returns the new Condition instance bound to this Lock instance.
  4. boolean tryLock() acquires the lock only when the lock is idle when called.
  5. boolean tryLock(long time, TimeUnit unit) If the lock is idle within the given waiting time and the current thread is not interrupted, acquire the lock.
  6. void unlock() release the lock.

Demo of multi-thread safety issues without using locks:

package com.company;

public class TestLock {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        new Thread(ticket, "1 ").start();
        new Thread(ticket, "2 ").start();
        new Thread(ticket, "3 ").start();
    }

}

class Ticket implements Runnable{

    private int tick = 100;


    @Override
    public void run() {
        while(true){
            if(tick > 0){
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                }

                System.out.println(Thread.currentThread().getName() + "  " + --tick);
            }

        }
    }

} 

Look at the problem (part of the interception result):

3   10
1   8
2   8
3   8
2   7
1   7
3   7
1   6
2   5
3   4
3   3
1   3
2   3
3   2
1   0
2   1 

Now we use Lock to process:

package com.company;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestLock {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        new Thread(ticket, "1 ").start();
        new Thread(ticket, "2 ").start();
        new Thread(ticket, "3 ").start();
    }

}

class Ticket implements Runnable {

    private int tick = 100;
    private Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();
                if (tick > 0) {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                    }

                    System.out.println(Thread.currentThread().getName() + "  " + --tick);
                }
            } finally {
                lock.unlock();
            }


        }
    }

} 

Looking at the results (of course part of it), it perfectly solves the multi-thread safety problem:

2   20
2   19
2   18
2   17
2   16
2   15
2   14
2   13
2   12
2   11
2   10
2   9
2   8
2   7
2   6
2   5
2   4
2   3
2   2
2   1
2   0 

 

posted on 2017-03-30 23:54 Northwest Wild Wolf Reading (46) Comments (0) Edit collection Refresh comments refresh the page Top to post a comment registered user login, please login or register , visit the website home page. [Recommended] Over 500,000 VC++ source code: Large-scale industrial control, configuration\simulation, modeling CAD source code 2018!
[Recommended] One-stop deployment of WeChat applet with multi-scenario template customization
The latest IT news :
These places you visit may be Tencent's sites
. The food, clothing, housing and transportation you are used to are actually Ali's sites.
Huawei Cloud President Zheng Yelai: The public cloud competition is far from over and AI is overconsumed
Zuckerberg commemorates the 14th anniversary of the birth of FB: I have made all the mistakes you think of
Station A is cold, and millions of "monkeys" are homeless
more news... Latest Knowledge Base Articles :
Practice of Domain Driven Design in Internet Business Development
Step into Cloud Computing
Thread and Process from the Perspective of Operating System
Software Testing Transformation Road
Look at Recruitment Inside and Outside
More Knowledge Base Articles ... Nickname: Northwest Wild Wolf
Park Age: 4 years and 6 months
Followers: 34
Follow: 3 +Follow
< February 2018 >
day One two three four Fives six
28 29 30 31 1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 1 2 3
4 5 6 7 8 9 10

search for

   

Most used link

My tag

Essay classification

Essay file

My github

My personal blog site

Points and ranking

  • Credits-110533
  • Rank-2676

latest comment

Read the leaderboard

Comment leaderboard

Recommended ranking

Powered by: Template provided by: Hujiang Blog Copyright 2018 Northwest Wild Wolf