Basic knowledge of Java threads and thread pools and related interview questions

A concurrency and parallelism are similar but distinct i.e. (micro Concept):
Parallel: refers to two or more events occur at the same point in time;
Concurrency: refers to two or more events occur within the same period.

In the operating system, in a multiprogramming environment, concurrency refers to a period of time in a plurality of programs run simultaneously macroscopically, but a single CPU system, but each time there is only one program execution (time slices ), so that these programs can only be microscopically alternately performed in time division.
If a plurality of CPU in a computer system, these programs can execute concurrently can be assigned to a plurality of processors, multi-parallel execution of tasks, i.e., with each processor to process a program can be executed concurrently, so that, you can perform multiple programs at the same time, because it is microscopic, so we feel that multiple programs are executed simultaneously when using a computer.
So, when you buy a computer like to buy "core" and more, the reason is the "multi-core processors" computers can handle multiple programs simultaneously in parallel, thereby improving the operating efficiency of the computer.
Single-core processor computer certainly can not handle a plurality of tasks in parallel, a plurality of tasks can run concurrently on a single CPU.
Similarly, the thread is the same, from a macro point of view to understand the thread is running in parallel, but the analysis from the microscopic point of view it is a serial operation, a thread that is a thread to run when the system is only one CPU, threads execute multiple threads in a certain order, we call this situation is called thread scheduling.
I.e. CPU time slice allocated to the running time of the respective programs (small concept).

II process and thread:
the process is an application that runs in a memory. Each process has its own separate piece of memory space, an application can start multiple processes simultaneously. For example, in Windows, a running abc.exe is a process.
At this point we can deal with the problem while playing games and listening to music, we can design into two programs, one dedicated to playing games, a dedicated music.
But here, if you want to design a Zombies game, I have to open the N process to complete multiple functions, this design is clearly unreasonable.
Not to mention most operating systems do not require a process to access other processes memory space, which means that communication between processes is very convenient.
At this point we have to introduce the "thread" this technology to solve this problem.
Thread refers to a task execution process (control unit), a process that can concurrently run multiple threads, such as: multi-threaded download software.
Multitasking system that can run multiple processes, a process can perform multiple tasks, a process can contain multiple threads.
A process has at least one thread, in order to improve efficiency, you can open multiple tasks in a process , that is multi-threaded.
Multi-process: the operating system to run multiple programs at the same time.
Multithreading: multiple tasks running in the same process at the same time.
We view the Task Manager under Windows environment:
allows multiple tasks in the operating system, each task is a process, each process can perform multiple tasks simultaneously, each task is a thread.

The difference between processes and threads:
process: a separate memory space, data storage space (heap space and stack space) process is independent, there is at least one thread.
Thread: heap space is shared, stack space is independent of the thread resources consumed is also smaller than the process, can influence each other, also known as lightweight processes or processes yuan.
Because multiple threads in a process is running concurrently, consider from the microscopic point of view is a sequential, it all depends on which thread execution CPU scheduler (JVM to schedule), the programmer can not control.
We can multi-threaded concurrency seen as multiple threads to grab CPU resources at the moment, who will come running to grab resources, it also created a multi-threaded randomness.
Process Java program (a Java program running on the system) contains at least the main thread and garbage collection threads (background thread).
Thread scheduling:
computer usually has only one CPU, at any time can execute only one computer instruction, each process only obtain the right to use the CPU to execute instructions.
The so-called multi-process run concurrently, from a macro point of view, in fact, each process in turn get the right to use the CPU, respectively, to perform their tasks.
so, can run in the pool, there will be multiple threads in the ready state until the CPU, JVM is responsible for the scheduling of threads.
the JVM uses preemptive scheduling **, ** no time-sharing scheduling, it can can cause random results of multi-threaded execution.

State of the thread
1. Create a new state (New):
2. ready state (Runnable)
3. running state (Running
4. blocked (Blocked)
5. death state (Dead)
Here Insert Picture Description
. Thread over three advantages:
multi-threading as a multi task, complicated by the way, of course, that there are advantages:
you can not share memory between processes ①, and shared memory (heap memory) between threads is very simple.
need to re-allocate system resources to the process of creating process ② system, create many threads are a small price, thus achieving concurrent multitasking, multithreading higher efficiency.
support ③ Java language itself, built-in multi-threading capabilities, rather than simply as a first scheduling of the underlying system, simplifying multithreaded programming.

Multi-threaded download: can be understood as a thread is to download a file channel, multi-threading is simultaneously opened to download several channels. When the server is available for download using the downloader is shared bandwidth, at the same priority level, the overall total server will download threads equally.
Not difficult to understand, if you multi-thread, then download faster. Now popular download software to support multi-threading.
Multithreading is to synchronize multiple tasks, not to provide efficiency program, but to improve the efficiency of the system by improving the efficiency of resource use.
So now when you buy a computer, you should look at the number of threads of the CPU.

IV. How to run a process in Java code

//运行一个进程
public class ProcessDemo {
    public static void main(String[] args) throws IOException {
        //方式1:Runtime类的exec方法:
        Runtime runtime = Runtime.getRuntime();
        runtime.exec("notepad");//打开一个记事本
        //方式2:ProcessBuilder的start方法:
        ProcessBuilder pb = new ProcessBuilder("notepad");//打开一个记事本
        pb.start();
    }
}

V. way to create threads
① inherit the Thread class created
 by inheriting from Thread and override its run (), run method that is thread to perform tasks. After create a subclass of threads can be executed by calling the start () method.
 By inheriting the Thread class Thread achieve, can not be shared between multiple threads thread class instance variables. (Need to create different objects Thread, naturally not shared)

public class ThreadTest extends Thread {
    private int i = 0;

    @Override
    public void run() {
        for (; i < 50; i++) {
          System.out.println(Thread.currentThread().getName() + " is running " + i);
        }
    }

    public static void main(String[] args) {
        for (int j = 0; j < 50; j++) {
            if (j == 20) {
                new ThreadTest().start();
            }
          System.out.println(Thread.currentThread().getName() + " is running " + j);
        }
    }
}

② create threads through the Runnable interface class
need to define a class that implements the Runnable interface method, the interface and override run () method, the method is run thread of execution. Create an object Runnable implementation class, create a Thread object as a parameter target, this thread Thread object is the real object. By Thread class implements Runnable interface, it is a shared resource of each other.

public class RunnableTest implements Runnable {
    private int i ;
    @Override
    public void run() {
        for(;i<50;i++){
            System.out.println(Thread.currentThread().getName() + " -- " + i);
        }
    }
    public static void main(String[] args) {
        for(int i=0;i<100;i++){
            if(i==20){
                RunnableTest runnableTest = new RunnableTest() ;
                new Thread(runnableTest,"线程1").start() ;
            }
            System.out.println(Thread.currentThread().getName() + " is running " + i);
        }
    }
}

③ use Callable and Future create a thread
  inherits from the Thread class and implement Runnable can be seen, the above two methods can not have a return value, and can not throw the exception. And this is achieved Callable two interfaces, interfaces as Callable upgraded Runable interface, which provides a Call () method as executable threads, while allowing a return value.
  But Callable object can not be directly used as target Thread object, because Callable interface is a Java 5 new interface, not the sub-interface Runnable interface. The solution to this problem, on the introduction of Future interface that can accept the call () return value, RunnableFuture interface is a sub-interface Future interfaces Runnable interface and can be used as target Thread object. And, Future interface provides an implementation class: FutureTask.
  FutureTask realized RunnableFuture interfaces can be used as target Thread object.

public class CallableTest {
    public static void main(String[] args) {
        CallableTest callableTest = new CallableTest() ;
        //因为Callable接口是函数式接口,可以使用Lambda表达式
        FutureTask<Integer> task = new FutureTask<Integer>((Callable<Integer>)()->{
            int i = 0 ;
            for(;i<100;i++){
                System.out.println(Thread.currentThread().getName() + "的循环变量i的值 :" + i);
            }
            return i;
        });
        for(int i=0;i<100;i++){
            System.out.println(Thread.currentThread().getName()+" 的循环变量i :" + i);
            if(i==20){
                new Thread(task,"有返回值的线程").start();
            }
        }
        try{
            System.out.println("子线程返回值 : " + task.get());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

④ e.g. by using a thread pool Executor frame
biggest advantage Executor frame 1.5 is introduced after the submission and decoupling perform tasks. People simply want to perform a task Task description clearly, then submit. This is how Task to be executed, by whom executed, when executed, submitted do not care anymore. Specific point of speaking, submit a Callable object to the ExecutorService (such as the most common thread pool ThreadPoolExecutor), will get a Future object, call the Future object method waits for the results get enough. Executor inner frame using thread pool mechanism, which in java.util.cocurrent packet start threads controlled by the frame, and performs closed, concurrent programming operation can be simplified. Therefore, after Java 5, to start the thread Thread the start better than using methods Executor, except easier to manage, better efficiency (with the thread pool implementation, cost savings), there is the key point: this helps to avoid escape question - if we start a thread in the constructor, because another task may begin before the end of the constructor, this time may have access to half of the objects initialized with the Executor in the constructor.

Executor framework include: the thread pool, Executor, Executors, ExecutorService, CompletionService , Future, Callable and so on.
The Executor interface defines a method execute (Runnable command), the method receives a Runable example, which is used to perform a task, the task that is a class that implements Runnable interface. ExecutorService interface inherits from Executor interface, which provides a way to achieve a richer multi-threaded, for example, provides a closed ExecutorService own methods, as well as track one or more asynchronous tasks produce a Future methods. ExecutorService can call the shutdown () method to smoothly close ExecutorService, after the method is called, it would lead to ExecutorService stop accepting any new tasks and wait for task execution has been submitted to complete (the task has been submitted will be divided into two categories: one is already in execution, the other is not yet started execution), when all the tasks that have been submitted is finished will be closed ExecutorService. So we generally use this interface to implement and manage multi-threading.
ExecutorService life cycle includes three states: running, closes terminated. Created after entering run state, when calling the shutdown () method, will enter the off state, at this time means that ExecutorService no longer accept new tasks, but it has been submitted in the implementation of the task, when known has submitted after the implementation of the task, they reach the end state. If you do not call shutdown () method, ExecutorService would have been in a running state, constantly receiving new tasks, new tasks, the server generally do not need to close it, to maintain a straight run.
Executors provides a range of factory methods for creating the first thread pool thread pool returns have achieved ExecutorService interface.
public static ExecutorService newFixedThreadPool (int nThreads)
thread pool that creates a fixed number of threads.
public static ExecutorService newCachedThreadPool ()
Creates a cached thread pool thread call to execute will reuse previously constructed (if the thread is available). If an existing thread is not available, a new thread is created and added to the pool. Terminate and remove those threads that have not been used for 60 seconds from the cache.
public static ExecutorService newSingleThreadExecutor ()
to create a single threaded Executor.
public static ScheduledExecutorService newScheduledThreadPool (int corePoolSize)
to create a thread pool to support regular and periodic task execution, can be used to replace the Timer class in most cases.
Executors These four methods are used in the thread ThreadFactory established, the following four methods above to be compared

newCachedThreadPool() Cache-type pool, first check the thread pool has no previously established, and if so, on reuse. If not, build a new thread to join a short buffer pool asynchronous task type commonly used to perform some type of pond survival and therefore Not too many in number SERVER daemon type with connection-oriented. But for the short term survival asynchronous task, it is the first choice of Executor. Can reuse the threads in the thread pool must be timeoutDLE, the default timeout is 60s, long beyond the DLE, thread instance will be terminated and removed from the pool. Note that threads into CachedThreadPool have to worry about its end, more than TIMEOUT inactivity, it will automatically be terminated
newFixedThreadPool(int) newFixedThreadPool and cacheThreadPool almost as well as be able to reuse it with, but not ready to build a new thread its uniqueness: at any point in time, can only have a fixed number of active threads exist at this time if there is a new thread to be created, only put in another waiting in the queue until the current thread, a thread terminates directly out of the different pond and cacheThreadPool, FixedThreadPool no IDLE mechanism (may have, but since the document did not mention, must be very long, similar dependence upper TC or UDPDLE mechanism and the like), so FixedThreadPool most stable for some very very formal fixed concurrent threads, and more from the source code for the server method of watching, cache pool and pool fixed calls is the same underlying pool, but different parameters: fixed pool of threads a fixed number, and it is 0 seconds IDLE (no
newScheduledThreadPool(int) Scheduling this type thread pool thread pool may in turn delay execution by schedule, or cycle execution
SingleThreadExecutor() Single-thread embodiment, the pool at any time only one thread with the fixed pool and the pool and cache the same underlying pool, but the number of threads is 1-1,0 seconds IDLE (no IDLE)

In general, CachedTheadPool usually created during program execution with the same number of threads needed, and then stops when it recovered the old thread creates a new thread, so it is a reasonable choice for the Executor only if this approach will cause problems (for example, it requires a lot of threads when long connection-oriented), the only need to consider FixedThreadPool.
Executor execute Runnable tasks
get ExecutorService instance by Executors of more than four static factory method, then calls the instance's execute (Runnable command) method can be. Once Runnable task passed to execute () method, in which a thread on automatically

public class TestCachedThreadPool {
    public static void main(String[] args){
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++){
            executorService.execute(new TestRunnable());
            System.out.println("************* a" + i + " *************");
        }
        executorService.shutdown();
    }
}

class TestRunnable implements Runnable{
    public void run(){
        System.out.println(Thread.currentThread().getName() + "线程被调用了。");
    }
}

VI. Face questions
① threads and processes What is the difference?
A process is an independent (self contained) operating environment, it can be seen as a program or an application. The thread is a task carried out in the process. A thread is a subset of the process, a process can have a lot of threads, each thread in parallel to perform different tasks. Different processes using different memory space, and all threads share a same memory space. Do not confuse it and stack memory, each thread has a separate stack memory used to store local data.

②Thread class start () and run () method What is the difference?
Call start () method will start a new thread; if called directly Thread's run () method, its behavior will be the same as ordinary methods; To execute our code in a new thread, you must use Thread.start () method.

③ with Runnable or Thread?
We all know that you can inherit the Thread class or Runnable interface calls to implement threads, the problem is to create threads which way is better? Under what circumstances to use it? This question is easy to answer if you know Java does not support multiple inheritance classes, but allows you to call multiple interfaces. So if you want to inherit from other classes, of course, is to call the Runnable interface better.

④Runnable and Callable What is the difference?
Runnable and Callable represent those tasks to be performed in different threads. From the beginning there JDK1.0 Runnable, Callable in JDK1.5 increased. The main difference is the Callable call () method returns a value and throw an exception, but the Runnable run () method do not have these features. Callable Future object may return loaded with the calculation result.

⑤ What is the Executor framework?
Executor framework was introduced in Java 5, Executor framework is a framework based on a set of asynchronous task execution policy calls, scheduling, execution and control of.
Unlimited creating a thread may cause application memory overflow, so create a thread pool is a better solution, because you can limit the number of threads and can be recycled these threads. You can very easily create a thread pool using the Executor framework.

What ⑥Executors class is?
Executors provides tools method Executor, ExecutorService, ScheduledExecutorService, ThreadFactory and Callable classes. Executors can be used to easily create a thread pool.

Published 99 original articles · won praise 2 · Views 2619

Guess you like

Origin blog.csdn.net/weixin_41588751/article/details/105104603