Prepare for 2022 spring move - java-day3

java

  1. java lock
    • Fair lock: it refers to that multiple threads acquire locks in the order of applying for locks, which is similar to queuing for meals and arriving first come first served
    • Unfair lock: the order in which multiple threads acquire locks is not the order in which they apply for locks. It is possible that the thread that applies later may acquire locks first than the thread that applies first. In the case of high concurrency, priority reversal or starvation may occur
    • Reentrant lock (recursive lock): after the outer function of the same thread obtains the lock, the inner recursive function can still obtain the code of the lock. When the same thread obtains the lock in the outer method, it will automatically obtain the lock when entering the inner method, that is, the thread can enter the code block synchronized with any lock it already has (to avoid deadlock)
    • Spin lock: the thread trying to acquire the lock will not block immediately, but will try to acquire the lock in a circular way. This has the advantage of reducing the consumption of context switching, but the disadvantage is that the cycle will consume CPU
    public final int getAndAddInt(Object var1, long var2, int var4) {
        int var5;
        do {
            var5 = this.getIntVolatile(var1, var2);
        } while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));
    
        return var5;
    }
    
    • Exclusive lock (write lock): this lock can only be held by one thread at a time. Both ReentrantLock and synchronized are exclusive locks.
    • Shared lock (read lock): it means that the lock can be held by multiple threads. For ReentrantReadWriteLock, its read lock is a shared lock and its write lock is an exclusive lock. The shared lock of read lock can ensure that concurrent reading is very efficient. The processes of reading, writing, reading and writing are mutually exclusive.
      • Write operation: atom + exclusive. The whole process must be a complete unity. The middle cannot be divided or interrupted.
        2. (synchronization tool class) CountDownLatch: latch
    • countDown() method: decrements the count of latches
    • await() method: causes the current thread to wait until the latch counts down to zero, unless the thread is interrupted
    public class CountDownLatchDemo {
        public static void main(String[] args) throws InterruptedException {
            CountDownLatch countDownLatch = new CountDownLatch(6);
    
            for (int i = 1; i <= 6; i++) {
                new Thread(() -> {
                    System.out.println(Thread.currentThread().getName() + "\t After self-study, go out of the classroom");
                    countDownLatch.countDown();
                }, String.valueOf(i)).start();
            }
    
            countDownLatch.await();
            System.out.println(Thread.currentThread().getName() + "\t There is no one in the classroom");
    
        }
    }
    
  2. (synchronization tool class) CyclicBarrier: Circular barrier
    • Function: make all threads wait for completion before proceeding to the next step. Scene: gather 7 dragon balls to summon the Dragon
    • Common constructor
    // First parameter: number of threads
    // The second parameter: thread, which is the action to be performed after all threads are completed
    public CyclicBarrier(int parties, Runnable barrierAction) {
        if (parties <= 0) throw new IllegalArgumentException();
        this.parties = parties;
        this.count = parties;
        this.barrierCommand = barrierAction;
    }
    
    • await() method: blocking threads
    public class CyclicBarrierDemo {
        public static void main(String[] args) {
            CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {
                System.out.println(Thread.currentThread().getName() + "\t#######\t summon dragon successfully ");
            });
    
            for (int i = 1; i <= 7; i++) {
                final int tempInt = i;
                new Thread(() -> {
                    System.out.println(Thread.currentThread().getName() + "\t Jiqidi" + tempInt + "Dragon Ball");
                    try {
                        cyclicBarrier.await();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }, String.valueOf(i)).start();
            }
        }
    }
    
    Operation results:
  3. Semaphore
    • It is mainly used for two purposes: one is for mutually exclusive use of multiple shared resources, and the other is for controlling the number of concurrent threads
    • Scene: competing for parking space
    public class SemaphoreDemo {
        public static void main(String[] args) {
            Semaphore semaphore = new Semaphore(3);// Simulate 3 parking spaces
    
            for (int i = 1; i <= 6; i++) {
                new Thread(() -> {
                    try {
                        semaphore.acquire();
                        System.out.println(Thread.currentThread().getName() + "\t Grab a parking space");
                        TimeUnit.SECONDS.sleep(3);
                        System.out.println(Thread.currentThread().getName() + "\t Leave the parking space after parking for 3 seconds");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        semaphore.release();
                    }
                }, String.valueOf(i)).start();
            }
        }
    }
    

algorithm

  • Square of ordered array
    Give you an integer array nums sorted in non decreasing order, and return a new array composed of the square of each number. It is also required to sort in non decreasing order.
    Example 1:
Input: nums = [-4,-1,0,3,10]
Output:[0,1,9,16,100]
Explanation: after squaring, the array becomes [16,1,0,9,100]
After sorting, the array becomes [0,1,9,16,100]

Source: LeetCode
Link: https://leetcode-cn.com/problems/squares-of-a-sorted-array
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.
Solution 1: violence ranking. After each number is squared, then sort

class Solution {
    public int[] sortedSquares(int[] nums) {
        int left = 0, right = nums.length-1;
        while (left <= right) {
            nums[left] = nums[left] * nums[left];
            left++;
        }
        Arrays.sort(nums);
        return nums;
    }
}

Solution 2: Double finger needle method - the array is actually orderly, but the negative square may become the maximum number. Then the maximum square of the array is at both ends of the array, either the leftmost or the rightmost. It can't be in the middle. Specifically, i points to the far left and j points to the far right.
Define a new array result, which is the same size as the original array, and let k point to the end of the result array.
If a [i] * a [i] < A[j] * A[j], result[k –] = A[j] * A[j].

If A[i] * A[i] > = a [J] * a [J], then result[k –] = A[i] * A[i].

class Solution {
    public int[] sortedSquares(int[] nums) {
        int left = 0, right = nums.length - 1;
        int[] result = new int[nums.length];
        int index = result.length-1;
        while (left <= right) {
            if (nums[left] * nums[left] < nums[right] * nums[right]) {
                result[index--] = nums[right] * nums[right];
                right--;
            } else {
                result[index--] = nums[left] * nums[left];
                left++;
            }
        }
        return result;
    }
}

Keywords: Java

Added by Nilanka on Fri, 21 Jan 2022 02:22:07 +0200