2021 latest Ali Java advanced interview questions and answers, three concurrent tool classes frequently asked in interviews

Semaphore is a count based semaphore.

It can set a threshold. Based on this, multiple threads compete to obtain the license signal and return it after making their own application. When the threshold is exceeded, the thread application license signal will be blocked.

Semaphore can be used to build some object pools and resource pools, such as database connection pool. We can also create semaphore with a count of 1 as a mechanism similar to mutual exclusion lock, which is also called binary semaphore, indicating two mutually exclusive states. Its usage is as follows:

The availablepermissions function is used to get the number of resources currently available

wc.acquire(); // Apply for resources

wc.release();// Release resources

Demand: there are only 3 technicians in a massage shop, but there are 10 old drivers to massage. What should we do?

Suppose that the numbers of 10 people are 1-10, and No. 1 comes to the technician first and No. 10 comes to the technician last. Then there must be available technicians for smooth massage when coming from the 1st to the 3rd. When coming from the 4th, you need to see whether someone in the front three has finished massage. If someone comes out, go in for massage, otherwise wait.

In the same way, No. 4-10 also needs to wait for the person who is massaging to come out before going in for massage. Code:

package cn.enjoy.mt;

import java.util.Random;
import java.util.concurrent.Semaphore;

class UserThrad extends Thread {
    private String name;
    private Semaphore jsShop;

    public UserThrad(String name, Semaphore jsShop) {
        this.name = name;
        this.jsShop = jsShop;
    }

    @Override
    public void run() {
        // The remaining technicians
        int availablePermits = jsShop.availablePermits();
        if (availablePermits > 0) {
            System.out.println(name + ",I found my little sister....");
        } else {
            System.out.println(name + ",It's a pity that we have to wait...");
        }
        try {
            // Apply for technician
            jsShop.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(name + "Start massage" + ",Number of technicians left:" + jsShop.availablePermits());
        try {
            Thread.sleep(new Random().nextInt(1000));
        } catch (Exception e) {

        }
        System.out.println(name + "The massage is over!,comfortable");
        // Release technician
        jsShop.release();
    }
}

public class SemaphoreTest {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(4);
        for (int i = 1; i <= 10; i++) {
            UserThrad userThrad = new UserThrad("The first" + i + "personal", semaphore);
            userThrad.start();
        }
    }

}

typora-copy-images-to: img
typora-root-url: img

1. Three concurrent tools frequently asked in interviews

If you are looking for a job, this article is tailored for you. Don't think about it. You will be asked during the concurrent programming interview. Here are three concurrent programming tools you often ask during the interview

The three classes described below are all from Java util. Under concurrent package,.

At least you need to know what they are for, and the code listed below also suggests you run

1.1. ** (* * counter) CountDownLatch

It can realize the function similar to counter

For example, there is a task task1, which can only be executed after all the other two threads are executed. It's time to consider CountDownLatch to realize this function.

CountDownLatch is implemented through a counter. The initial value of the counter is the number of threads.

Whenever a thread executes CDL The value of the counter will be decremented by 1. When the initial value reaches 0, it indicates that all threads have completed the task, and then the threads waiting on the lock can resume executing the task.

package cn.enjoy.mt;
import java.util.concurrent.CountDownLatch;
public class CountDownLatchTest {
    public static void main(String[] args) throws InterruptedException {

        CountDownLatch cdl = new CountDownLatch(2); //2 here represents that countDown() must be executed twice
        new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + ",begin...");
                cdl.countDown();
                System.out.println(Thread.currentThread().getName() + ",end...");
            }
        }).start();

        new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + ",begin...");
                cdl.countDown();//The counter value is subtracted by 1 at a time
                System.out.println(Thread.currentThread().getName() + ",end...");
            }
        }).start();
        cdl.await();// Subtract 0 to continue the recovery task
        System.out.println("Two Thread completion of enforcement....");
        System.out.println("The main thread continues execution.....");
        for (int i = 0; i <10; i++) {
            System.out.println(Thread.currentThread().getName()+",i:"+i);
        }
    }
}

It can be seen from the results that the main thread will continue to execute only after the execution of the two sub threads is completed

1.2. ** (* * barrier) CyclicBarrier

CyclicBarrier also specifies a number during initialization, and then calculates that CyclicBarrier has been called The number of threads await() entered to wait.

When the number of threads reaches this number, all threads entering the waiting state are awakened and continue.

CyclicBarrier, as its name means, can be regarded as an obstacle. All threads must be assembled before they can pass through this obstacle together.

CyclicBarrier can also take a Runnable parameter initially. This Runnable task is executed after the number of cyclicbarriers reaches and before all other threads are awakened.

package cn.enjoy.mt;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
class Writer extends Thread {
    private CyclicBarrier cbr;
    public Writer(CyclicBarrier cbr) {
        this.cbr = cbr;
    }
    @Override
    public void run() {
        try {
            System.out.println("thread " + Thread.currentThread().getName() + ",Writing data");
            Thread.sleep(3000);
            System.out.println("thread " + Thread.currentThread().getName() + ",Write data succeeded.....");
            cbr.await();
            System.out.println("All threads finished executing..........");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
public class CyclicBarrierTest {
    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
        for (int i = 0; i < 5; i++) {
            Writer writer = new Writer(cyclicBarrier);
            writer.start();
        }
    }
}

1.3. ** (* * count Semaphore) Semaphore

Semaphore is a count based semaphore.

It can set a threshold. Based on this, multiple threads compete to obtain the license signal and return it after making their own application. When the threshold is exceeded, the thread application license signal will be blocked.

Semaphore can be used to build some object pools and resource pools, such as database connection pool. We can also create semaphore with a count of 1 as a mechanism similar to mutual exclusion lock, which is also called binary semaphore, indicating two mutually exclusive states. Its usage is as follows:

The availablepermissions function is used to get the number of resources currently available

wc.acquire(); // Apply for resources

wc.release();// Release resources

Demand: there are only 3 technicians in a massage shop, but there are 10 old drivers to massage. What should we do?

Suppose that the numbers of 10 people are 1-10, and No. 1 comes to the technician first and No. 10 comes to the technician last. Then there must be available technicians for smooth massage when coming from the 1st to the 3rd. When coming from the 4th, you need to see whether someone in the front three has finished massage. If someone comes out, go in for massage, otherwise wait.

In the same way, No. 4-10 also needs to wait for the person who is massaging to come out before going in for massage. Code:

package cn.enjoy.mt;

import java.util.Random;
import java.util.concurrent.Semaphore;

class UserThrad extends Thread {
    private String name;
    private Semaphore jsShop;

    public UserThrad(String name, Semaphore jsShop) {
        this.name = name;
        this.jsShop = jsShop;
    }

    @Override
    public void run() {
        // The remaining technicians
        int availablePermits = jsShop.availablePermits();
        if (availablePermits > 0) {
            System.out.println(name + ",I found my little sister....");
        } else {
            System.out.println(name + ",It's a pity that we have to wait...");
        }
        try {
            // Apply for technician
            jsShop.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(name + "Start massage" + ",Number of technicians left:" + jsShop.availablePermits());
        try {
            Thread.sleep(new Random().nextInt(1000));
        } catch (Exception e) {

        }
        System.out.println(name + "The massage is over!,comfortable");
        // Release technician
        jsShop.release();
    }
}

public class SemaphoreTest {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(4);
        for (int i = 1; i <= 10; i++) {
            UserThrad userThrad = new UserThrad("The first" + i + "personal", semaphore);
            userThrad.start();
        }
    }

}

Is that enough? No, not enough!

Getting familiar with Ali's interview questions in previous years in advance must be of great help to the interview, but as a technical career, having solid technology in your hand is the most useful weapon for you to face the interviewer, which is the confidence emanating from the inside.

When preparing for Ali, I spent the most time learning technology, accounting for 70% of all my learning plans. These are some learning notes that I thought were very good during my study

CodeChina open source project: [analysis of Java interview questions of front-line large manufacturers + core summary learning notes + latest explanation Video]

Why should I write this article? In fact, I think learning can't stop. Sharing and discussing with you on the Internet can not only meet more people, but also expand my horizons and learn more technologies. I will also share technologies on csdn, blog, nuggets and other websites, which is also a way of learning.

That's all for today. Thank you for your attention. I'll share more dry goods to you in the future!

.net/m0_60958482/java-p7)**

Why should I write this article? In fact, I think learning can't stop. Sharing and discussing with you on the Internet can not only meet more people, but also expand my horizons and learn more technologies. I will also share technologies on csdn, blog, nuggets and other websites, which is also a way of learning.

That's all for today. Thank you for your attention. I'll share more dry goods to you in the future!

[external chain picture transferring... (IMG vxneenfv-1630718624010)]

[external chain picture transferring... (img-z2JMPrFG-1630718624012)]

[external chain picture transferring... (img-yvKeLdKn-1630718624013)]

Keywords: Java Back-end Interview Programmer

Added by kostik on Fri, 17 Dec 2021 09:29:56 +0200