"Proposed Heart" to come to more than 15 threads face questions once cool in the end (1.1w words carefully finishing)


This article is for ** "Proposed Collection" 200MB manufacturers interview document finishing summary strongest interview exam in 2020 "CoreJava chapter" ** write the answers, all the relevant articles already included in the code repository cloud: https://gitee.com / bingqilinpeishenme / Java-interview

Many thousands of water always love to see the okay to praise, to force Austria

This article is a multi-threaded answer interview questions Part I: Basic Concepts + thread pool thread lock + other face questions will be written in the next.

Part situation:

  • A total of 15 face questions
  • Illustrations, the concept of mutual aid codes +
  • More than 1.1w word children, it is recommended to facilitate future access to collection

1. What is the process? What is a thread?

Process (process) and thread (thread) is the basic concept of the operating system, but they are more abstract, not easy to grasp.
Recently seen an explanation on Ruan Yifeng blog, I feel very good, to share with small partners.

  1. ** core computer is CPU, it assumed all computing tasks. ** It's like a factory, always running.

  2. Assumed power plant is limited, it can only supply a workshop. In other words, a workshop started when the plant must shut down the other. Meaning behind is that a single CPU can run only one task .

  3. Process like the factory floor, it represents a single CPU can handle the task . At any one time, CPU always run a process, other processes is not running.

  4. A workshop, there are many workers. They complete a collaborative task

  5. Thread-like worker ratio in the workshop. A process can include multiple threads .

process

The so-called process is run in a multitasking operating system, the process is a unit of computer task scheduling, the operating system to start a program in time, will create a process, JVM is a process. Between the process and the process is isolated from each other, each process has its own memory space.

Principles of Computer concurrency are: CPU time slice division performed alternately, parallel macro, micro serial. Similarly, the separation of smaller tasks scheduling unit is the thread on the basis of the process, our so-called multi-threading is a process complicated by multiple threads.

Thread

We mentioned above, a process and can issue multiple threads, and the thread is the smallest unit of task execution, specifically, the process execution of a program sequence is a thread, our main is a common thread (the main thread).

Composed of threads

Want to have a thread, there is such an integral part of some, there are: CPU time slice, data storage, code.
There are CPU time slice, the data storage space is what we often say that the heap space and stack space allocated to the operating system, between threads, the heap space is shared by multiple threads, stack space is independent of each other, the benefits of doing so not only convenient, but also reduce a lot of waste of resources. Code not do too much to explain, no code Mao put forward a multi-threaded.

2. What is thread safe?

About what is thread-safe, why is there a security thread, and why you need a lock, I wrote a short story in three or four years.

Several small concepts
critical resource: When multiple threads access the same object, which is called the critical resources
atomic operations: an integral resource in critical operation called atomic
thread-safe: multiple threads simultaneously access the same object, not destroyed segmentation operation, data inconsistencies can occur

"Law of the jungle" thread in the world

Hello everyone, I am Wang sledgehammer, my goal is to be the CEO ... take the wrong amount embarrassed the script. Hello everybody, my name is 0x7575, is a thread of my life line is always ideal to get the fastest CPU.

Give you about the world thread, the thread of the world is a jungle world, always scarce resources, what should grab, which I was fortunate to get a few nanoseconds CPU, for int a = 20 plus 1 operation once, when I remove from memory a, by incrementing after losing the CPU, memory after the break ready to write, I was surprised to find: the memory of a time that has become 22.

There must be a thread in my absence modify the data, I have a dilemma, many threads also tried to persuade me not to write, but forced instruction, I can only cover 21 into memory does not conform to my arithmetic logic 22.

These are just a small accident, a similar thing in the world after another thread, so although we each have a thread due diligence, but it seems that we humans are the culprit causing data insecurity.

This is how wronged ah, the world has always been a thread competitive world, especially for some shared variables, shared resources (critical resources), while it normal when multiple threads compete for the use of things. Unless eliminate shared resources, but this is not possible, then things started deadlocked.

Thread the world appears a lock

Fortunately, it still smart people, it was thought a good way to solve the problem. We do not know who thought of the note, but the note does solve part of the problem, solution is to lock .

You want to set a lock code to operate it? If you want to go grab a lock, then get the lock code can be locked do whatever they want, if not get the lock, then you can only block the door waiting, because too many other threads, it also has become a social phenomenon (state), the social phenomenon is named blocked thread.

Sounds simple, but in fact there are many locking detailed provisions, the government released details of "a number of provisions synchronzied use" and "a number of provisions regarding the use of the Lock" and later released.

Between the threads and the threads are shared memory, when the multi-thread operation on the shared memory has several problems are inevitable, race conditions (race condition) and memory visibility.
** race conditions: ** When multiple threads access the same object and the operation time of the final results and the timing related to the implementation of correctness is not capable of human control, may be right or may be incorrect. (As an example)

Speaking above the lock is to solve this problem, common solutions are:

  • Use the synchronized keyword
  • Use explicit lock (Lock)
  • With atomic variables

** Memory Visibility: ** about visibility issues from the first memory with memory and cpu's talking about, is a hardware memory, execution speed is hundreds of times slower than the CPU, so in the computer, when the operation is performed in the CPU, and memory operations are not performed each time data exchange, but the first CPU to write some data in the buffer (register and cache levels) is written to memory at the end. This process is its fast, single-threaded and without any problems.

But in a multithreaded there is a problem, a thread of a data memory made changes, but did not promptly written to memory (temporarily stored in the cache); this time another thread of the same data to make changes time to get that memory has not been modified data, that is a thread to modify a shared variable, and another thread can not be seen right away, and even never see.

This is the visibility of the problem of memory.

A common solution to this problem is:

  • Use the volatile keyword
  • Use the synchronized keyword or explicit lock synchronization

3. What are the state of the thread?

A thread does not execute immediately after the start, but in a ready state (Ready) , the ready state is a kind of state of the thread, the thread is in this state means that everything is ready, waiting for the system to allocate time slots. Why did not immediately run it, because at the same time only one thread can get a slice of time to run, start a new thread when it starts thread (the main thread) is running, the only other end of the main thread, it is a chance to get a slice of time run.

** state of the thread: ** initial state (New), Ready (Ready), running state (Running) (Special Note: In the definition of grammar, the ready state and run state is a state Runable), wait state (Waitering ), termination status (terminated)

  1. The initial state (New)
    1. Thread object is created, is the initial state, this time the thread object is just an ordinary object, not a thread
  2. Runable
    1. ** ready state (Ready): ** start after performing the method, the ready state, waiting to be assigned to the time slot.
    2. ** running state (Running): ** CPU threads to get started. Thread is the running time of the CPU is not permanent hold until the end of the run, it may not have finished the time slice expires, they were deprived of the right to use the CPU, and then will be in a wait state.
  3. Wait state (Waiting)
    1. Wait state is divided into time-limited wait and wait indefinitely, waiting for the so-called time-limited initiative is the thread goes to sleep using sleep method, there is a certain time limit, then re-enter the time expires ready, waiting once again been selected CPU.
    2. And wait indefinitely bit different, indefinitely does not mean waiting for ever go on, but to no time limit, after one second may also be a lot of seconds. For reasons not the same enter the wait, possibly because the CPU time slice expires, it may be a time-consuming operation because (a database), or active call join method.
  4. Blocked (Blocked)
    1. Blocking state is actually a special wait state, other threads in a wait state is waiting for another thread to perform the end, waiting to get the right to use the CPU; and the thread is blocked waiting for more than just the CPU the right to use, primarily lock mark, did not get the lock token, even if the CPU is free there is no way to perform.
  5. Terminate the thread (Terminated)
    1. The thread has been terminated in the states.

4. wait distinction of sleep and

5. Wait difference and obstruction

6. Java thread creation in the way

  1. Inheritance Thread
  2. Implement Runnable
  3. Implement Callable interface, and use FutureTask
  4. Use the thread pool
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

public class NewThreadDemo {

    public static void main(String[] args) throws Exception {
        
        //第一种方式
        Thread t1 = new Thread(){
            @Override
            public void run() {
                System.out.println("第1种方式:new Thread 1");
            }
        };
        t1.start();
        
        TimeUnit.SECONDS.sleep(1);
        
        //第二种方式
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("第2种方式:new Thread 2");
            }
        });
        t2.start();

        TimeUnit.SECONDS.sleep(1);
        
        
        //第三种方式
        FutureTask<String> ft = new FutureTask<>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                String result = "第3种方式:new Thread 3";
                return result;
            }
        });
        Thread t3 = new Thread(ft);
        t3.start();
        
        // 线程执行完,才会执行get(),所以FutureTask也可以用于闭锁
        String result = ft.get();
        System.out.println(result);
        
        TimeUnit.SECONDS.sleep(1);
        
         //第四种方式
        ExecutorService pool = Executors.newFixedThreadPool(5);

        Future<String> future = pool.submit(new Callable<String>(){
            @Override
            public String call() throws Exception {
                String result = "第4种方式:new Thread 4";
                return result;
            }
        });

        pool.shutdown();
        System.out.println(future.get());
    }
}

7. Callable and Runnable of difference?

	class c implements Callable<String>{
		@Override
		public String call() throws Exception {
			return null;
		}
	}
	
	class r implements Runnable{
		@Override
		public void run() {
		}
	}

Same point:

  1. Both are interfaces
  2. Both need to start calling thread Thread.start

difference:

  1. As shown in the above code, the core Callable call method, allowing the return value, the core run method is runnable, no return value
  2. call method can throw an exception, but the run method does not work
  3. Because runnable is java1.1 there, so he returned values ​​do not exist, the latter has been optimized java1.5, there have been callable, have a return value and Throws
  4. runnable and callable can be applied to executors. The class supports only runnable thread

8. What is the thread pool? what is the benefit?

Speaking thread pool will think tank technology, the core idea is one of the most precious resources into a pond; each use to obtain from the inside, then run back into the pool for use by others, a little eat mess the meaning of.

Java thread pool has the following advantages:

  1. A thread is a scarce resource, not frequently created.
  2. Decoupling effect; to create a completely separate thread to perform easy maintenance.
  3. Should put it into a pond, can be multiplexed to other tasks.

9. Create a thread pool mode

  1. By Executors class
  2. ThreadPoolExecutor by category

In Java, we can create a thread pool by Executors class , common API are:

  1. Executors.newCachedThreadPool (): unlimited thread pool.
  2. Executors.newFixedThreadPool (nThreads): create a thread pool of fixed size.
  3. Executors.newSingleThreadExecutor (): Create a single thread pool thread.
  4. Executors.newScheduledThreadPool()
  5. Executors.newWorkStealingPool (int) java8 added, using currently available processors on the machine level parallelism as its

The above method of creating a thread pool, in fact, JDK has given us written, can be used to ready to use. But as long as we view the source code of the above methods you will find:

public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}

Using the above methods are actually ThreadPoolExecutor classes.

So the second way is to create a thread to create their own through new ThreadPoolExecutor.

10. Executors There are so many ways to create a thread pool, with the development of which is better?

The answer: a do not.

From "Ali Baba Java Development Manual" can be seen

For detailed explanation of the parameters see the next question.

11. How a custom thread pool by ThreadPoolExecutor? That is what is important parameter thread pool there?

In the last issue, we mentioned a thread pool that creates new ThreadPoolExecutor the way through, then, how to create it? At the time of creation, which parameters they need it?

We look at the direct source ThreadPoolExecutor construction method, as follows:

public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.acc = System.getSecurityManager() == null ?
                null :
                AccessController.getContext();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

Parameters are dense, so what are these arguments?

The process is generally

  1. After you create a thread pool, has the task of submitting to the thread pool, it will start with the implementation of the core thread
  2. If the task continues to increase, corePoolSize run out and the task queue is full, and this time the thread pool will increase the number of threads, to increase the maximum number of threads
  3. If the task continues to increase at this time, due to the number of threads that have reached the maximum number of threads, also waiting queue is full, and this time the thread pool is actually no ability to perform new tasks, it will refuse to adopt policies
  4. If the task is decreased, there will be many threads are not needed, doing nothing, as long as these threads idle for more than the idle thread time, will be destroyed, until a few remaining threads corePoolSize.

By the above parameters can be provided a flexible thread pool, the following sample code:

/**
* 获取cpu核心数
*/
 private static int corePoolSize = Runtime.getRuntime().availableProcessors();

    /**
     * corePoolSize用于指定核心线程数量
     * maximumPoolSize指定最大线程数
     * keepAliveTime和TimeUnit指定线程空闲后的最大存活时间
     */
    public static ThreadPoolExecutor executor  = new ThreadPoolExecutor(corePoolSize, corePoolSize+1, 10l, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(1000));

12. The underlying thread pool works?

About working principle and implementation process thread pool to show with two graphs

  1. After you create a thread pool, the task waiting for requests submitted over.
  2. When you call the execute () method to add a task request, the thread pool will do the following judgment:
    1. If the number of threads running less than corePoolSize, then immediately create a thread is created to run this task immediately.
    2. If the number of running threads is greater than or equal to corePoolSize, then this task in the queue .
    3. If the number of threads when the queue is full and running is also less than maximumPoolSize, it still has to create a non-core thread to run this task immediately.
    4. If the queue is full number of threads greater than or equal maximumPoolSize and running, then the thread pool starts saturation refuse to execute strategy .
  3. When a thread to complete the task, it will be removed from the queue a task to perform.
  4. When a thread is nothing more than a certain period of time (keepAlilveTime), the thread pool will judge:
    1. If the number of the currently running thread is more than corePoolSize, then the thread is stopped.
    2. So after all the tasks of the thread pool complete it will eventually shrink to the size of corePoolSize .

13. The saturation strategy talk thread pool, also called a denial strategy.

The so-called saturation strategy is: When the queue is already full, never made less than a new task, then, the maximum number of threads in the thread pool is also to maximum, mean that the thread pool does not have the ability to continue to perform new tasks, and this time no new job submission to the thread pool, how to deal with, is the saturation (denial) strategy

14. How rational allocation of a thread pool

Usually we need to determine the nature of the execution of these tasks.

  • IO-intensive tasks: As the thread was not always running, so you can configure the thread as much as possible, such as the number of CPU * 2
    • IO-intensive, that is, the task requires a lot of IO, that is a lot of congestion.
    • IO-intensive tasks running on a single thread will lead to waste a lot of CPU power wasted in waiting.
    • So IO-intensive tasks using multiple threads can greatly speed up the program to run, even on a single-core CPU, this acceleration is mainly the use of the blocking time is wasted.
  • CPU intensive tasks (a large number of complex operations) should be allocated fewer threads, such as the number corresponding to the size of the CPU. CPU-intensive means that the task requires a lot of computation, without obstruction, CPU runs at full speed.

Of course, these are the experience, the best way is optimum test configuration according to the actual situation.

15. How close the thread pool

Close the thread pool has two methods: shutdown()/shutdownNow().

  • shutdown() After performing stop accepting new tasks, task execution queue will finish.
  • shutdownNow() Also stopped accepting new tasks, but it will interrupt any task, the thread pool state to stop.

Close the code thread pool:

long start = System.currentTimeMillis();
for (int i = 0; i <= 5; i++) {
    pool.execute(new Job());
}
pool.shutdown();
while (!pool.awaitTermination(1, TimeUnit.SECONDS)) {
    LOGGER.info("线程还在执行。。。");
}
long end = System.currentTimeMillis();
LOGGER.info("一共处理了【{}】", (end - start));

pool.awaitTermination(1, TimeUnit.SECONDS)Will be inspected once every second if the execution is completed (state TERMINATED), when you exit from the while loop to show that the thread pool has been completely terminated.

References:

  1. A simple explanation of processes and threads
  2. Java- Multithreading Basics
  3. Java- Thread Synchronization
  4. Four ways to create a thread
  5. Callable and Runnable of difference
  6. Elegant and understanding how to use the thread pool
  7. "Ali Baba Java Development Manual"
  8. In-depth understanding of the principles of the thread pool papers

I welcome public concern number: deer teacher's notes Java, Java technology will be a long-term update graphic tutorials and video tutorials, Java learning experience, Java interview experience and practical development experience in Java.

Guess you like

Origin www.cnblogs.com/bingyang-py/p/12557507.html