This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

Synchronized with already

  • The first thing to answer is
    • becausesynchronizedThere is aJDKProvide the lock
      • The bottom layer involves the level of the instruction set, such as:
      1. The synchronization code block is implemented using the Monitorenter and Monitorexit directives

      2. The synchronization method is implemented using flags.

  • whileRenntranLockIs the lock implementation provided by java5
    • Is a set of mutex locks provided under the java.util.concurrent package

    • But compared with synchronized, it has many functions that synchronized cannot achieve

    • The most obvious example is RenntranLock’s ability to customize “fairness.

The concept of thread safety: ensuring that shared, modifiable states are correct in a multithreaded environment

  • Let’s look at the following code

public class test {
    public int state;
    public void testSafe(a) {
        while (state < 100000) {
            int i = state++;
            int j = state;

            if(i ! = j -1) {
                System.out.println("i is: " + i + "; j is: "+ j); }}}public static void main(String[] args) throws InterruptedException {
        test t = new test();
        Thread ta = new Thread() {
            @Override
            public void run(a) { t.testSafe(); }}; Thread tb =new Thread() {
            @Override
            public void run(a) { t.testSafe(); }}; ta.start(); tb.start(); ta.join(); tb.join(); }}Copy the code
  • Below is the output of the code
    • It is clear that concurrent thread modifications have occurredstateThe value of the

  • For the above code if plussynchronizedIf ๐Ÿ” is locked, there will be no value changes
synchronized (this) {while (state < 100000) {
        int i = state++;
        int j = state;

        if(i ! = j -1) {
            System.out.println("i is: " + i + "; j is: "+ j); }}}Copy the code
  • Synchronized (class){} synchronized(class){

    • While the use ofRenntranLockWhen a thread attempts to acquire an acquired lock
      • So this action is automatically successful
      • Fairness is a preference for giving the lock ๐Ÿ” to the thread that has waited the longest
      • The upper operation is to reduce thread hunger
  • ReentrantLock can be used like a normal object compared to synchronized

    • Various convenient methods provided by synchronized can be used to carry out fine synchronization operations, and even achieve use cases that are difficult to be expressed by synchronized, such as:
      • Attempt to obtain lock with timeout.

      • You can determine if there is a thread, or a particular thread, queuing to acquire the lock.

      • Can respond to interrupt requests.

    Queues associated with reentrant locks

public ArrayBlockingQueue(int capacity, boolean fair) {
   if (capacity <= 0)
       throw new IllegalArgumentException();
   this.items = new Object[capacity];
   lock = new ReentrantLock(fair);
   notEmpty = lock.newCondition();
   notFull =  lock.newCondition();
}
Copy the code
  • inArrayBlockingQueueWe can see in the source code
    • Both condition variables are from the sameReentrantLockcreated
public E take(a) throws InterruptedException {
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        while (count == 0)
            notEmpty.await();
        return dequeue();
    } finally{ lock.unlock(); }}Copy the code
  • When the queue is empty
    • takeThread callawait()Execute waiting to join the queue
    • It doesn’t just return, it formsBlockingQueueThe meaning of
    • This step is important innotEmptybody

The operation of entrance

private void enqueue(E x) {
    // assert lock.getHoldCount() == 1;
    // assert items[putIndex] == null;
    final Object[] items = this.items;
    items[putIndex] = x;
    if (++putIndex == items.length)
        putIndex = 0;
    count++;
    notEmpty.signal();
}
Copy the code
  • Enter the team to operate proudly passsignal()Completion notification thread
    • So throughsignal()andawait()The combination completes the closed loop of states