Java Interview Highlights: 25 Thread class-related interview questions and answers (a)

Java Interview Highlights: 25 Thread class-related interview questions and answers (a) .png

1. What threads are? What processes are? Both What is the difference and contact?

(1) A thread is the basic unit of CPU operate independently and scheduled separately; (2) process is the basic unit of resource allocation; both applications are executed with links: processes and threads are running an operating system program running base unit.

The difference between: (1) processes with separate address space, after a process crashes, will not have an impact on other processes in protected mode. (2) the thread just a different execution path of a process, thread has its own stack and local variables, but there is no separate address spaces between the threads, a thread to die is tantamount to the whole process dies.

The process is executed with the application, and the thread is a sequence of execution within a process. A process can have multiple threads. Thread also called lightweight processes.

2. Thread each process and what is the difference and cons?

The process is the smallest unit of resource allocation, the thread is the smallest unit of program execution.

Process has its own separate address space, each started a process, the system will allocate address space for it, set up a data table to maintain the code segment, stack and data segments, this operation is very expensive. The thread is a shared process data, using the same address space, so the CPU changes than the process takes a much smaller thread, while creating a thread overhead is much smaller than the process.

More convenient communication between threads, the thread in the same process share global variables, static variables and other data, and communication between processes carried out in a manner (IPC) communication. But how to handle the synchronization and mutual exclusion is the difficulty of writing multithreaded programs.

But the program more robust multi-process, multi-threaded program as long as there is a thread dies, the whole process is dead, too, and a process dies the other will not have impact on the process, because the process has its own separate address space.

Refer to article

3. Create a thread in several different ways? Which do you prefer? why?

There are three ways to create threads:

Inherited Threadclass

Implement RunnableInterface

Applications can use the framework to create a thread pool Executor

Implement Runnable接口this method is more popular because it does not need to inherit the Threadclass. In the case of application design we have inherited the other object, which requires multiple inheritance (but Java does not support multiple inheritance), only interfaces. At the same time, the thread pool is also very efficient, easy to implement and use.

4. Under thread interpretation outlined several available state?

Threads in the implementation process, can be in several states the following:

Ready (Runnable) : thread is ready to run, not necessarily immediately can begin execution.

Running (Running) : threaded code executing process.

Waiting (Waiting) : processing thread is blocked, waiting outside end.

Sleep (Sleeping) : the thread is forced to sleep.

I / O blocked (Blocked ON I / O) : Wait I / O operation is completed.

Synchronous blocking (Blocked ON Synchronization) : waiting to acquire the lock.

Death (Dead) : thread finishes execution.

5. What is the difference synchronization method and synchronized block is?

In the Java language, each object has a lock. Thread can use the synchronized keyword to get the lock on the object. synchronized keyword can be applied in the process level (coarse-grained locks) or the code block level (fine-grained locking).

Keyword Java language, when it used to modify a method or a block of time, to ensure that at most one thread executes the code in the same period of time.

(1), when the same target object in two concurrent threads to access this synchronized (this) synchronized block, a time only one thread to be implemented. Another thread must wait for the current thread to execute the code block after the completion of the implementation of the code block.

(2) However, when a thread to access the object of a synchronized (this) synchronized block, another thread can still access the object in a non-synchronized (this) synchronized block.

(3), is particularly critical when a thread to access the object of a synchronized (this) synchronized block, another object of all other threads synchronized (this) to access the synchronization code block will be blocked.

(4), the same applies to other examples of the third sync block. That is, when a synchronized one thread to access the object (this) synchronized block, it acquired the object lock this object. As a result, other threads to access all objects of the object synchronization code sections have been temporarily blocked.

(5), the above rule applies to other objects lock.

6. In the internal monitor (Monitor), how do thread synchronization? Program should do what level of sync?

Monitor and lock in the Java virtual machine is a piece of use. Monitor monitors a sync block, to ensure that only one thread is executing synchronized block. Each of the monitors and associated with an object reference. Thread is not allowed to perform synchronization code before acquiring the lock.

7. What is a deadlock (deadlock)?

Both processes are waiting for each other when finished to continue down the deadlock occurs. The result is that the two processes are caught in endless waiting.

8. How to ensure N N threads can access resources while not leading to a deadlock?

When using multiple threads, a very simple way to avoid deadlock is: Specifies the order of acquisition of the lock, and forcibly acquiring a lock thread in the specified order. Thus, if all threads are locking and releasing locks in the same order, it will not deadlock appeared.

9. How to avoid deadlocks?

Four necessary conditions for multi-threaded deadlock: the mutually exclusive conditions: a resource can only be used by a process. And requests to maintain conditions: when a resource request due process and blocked access to resources that have been kept tightly. Inalienable tune: the process has access to resources, not used before completion, it can not be denied. Loop wait condition: form a head to tail cyclic relationship between several processes waiting for a resource.

As long as the destruction of any of these conditions, you can avoid deadlock, the simplest of which is to break the cycle of waiting loop conditions. In the same order to access the object, load lock, release the lock.

10. Thread class start () and run () method What is the difference?

start () method is used to start a new thread is created, so that the thread state is created becomes runnable. When you call the run () method will only be invoked in the original thread, no new thread is started, start () method will start a new thread. If we call the Thread's run () method, it will act the same way as ordinary, run directly run () method. In order to execute our code in a new thread, you must use Thread.start () method.

11. Java in 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.

12. Java What is in race conditions?

In most practical multi-threaded applications, two or more threads need to share access to the same data. If i threads access the same object, and each thread calls a method to modify the state of the object, what would happen? Imagine, stepped thread in each others' feet. According to the order of threads access the data, it may cause corrupted objects. Such a situation commonly referred to as a race condition.

13. Java in how to stop a thread?

JavaIt provides a rich API but does not provide an API to stop the thread. JDK 1.0Some would have been like stop(), suspend()and resume()the control method, but because of the potential threat of deadlock. Therefore, in subsequent versions of the JDK they have been abandoned, after the designer of the Java API would not provide a compatible and thread-safe way to stop a thread. When run()or call()when executing the method of thread will automatically end, if you want to end a thread manually, you can use volatilea Boolean variable to exit the run()loop or cancel the task to interrupt thread method.

14. Java in notify and notifyAll What is the difference?

One obvious reason is that the lock is JAVA provide object-level and not the thread level, each object has a lock obtained by a thread. If a thread needs to wait for some lock then call the object wait () method to sense. If the wait () method defined in the Thread class, which thread is waiting for the lock is not obvious. Simply put, because the wait, notify and notifyAll are lock-level operations, so they are defined in the Object class because locks belong to the object.

Synchronized set of concurrent collection 15. Java What is the difference?

Concurrent collections are synchronized set of multi-threading and concurrency provide a suitable set of thread-safe is, however, complicated by a collection of higher scalability. In the Java1.5prior programmers to use and the only set of synchronization in multithreaded concurrent time can cause contention, hindering the expansion of the system. Java5 introduced concurrent collections, like ConcurrentHashMap, not only provides thread safety also locks the isolation and internal partitions and other modern technology to improve scalability.

16. What is the thread pool?

Thread pool is a multithreaded processing forms, will be submitted to the task processing thread pool thread pool to perform tasks handed over to be managed. If each request to create a thread to handle, then the server's resources will soon be exhausted, often using a thread pool thread creation and destruction can be reduced and each worker thread can be reused, you can perform multiple tasks .

17. Why use a thread pool?

Create threads and to destroy threads spending is relatively large, the time may be longer than the time to deal with business. Such frequent thread creation and destruction of threads, plus business worker threads consume system resources of time, it may lead to insufficient system resources. (We can put the process of creating and destroying threads removed)

18. What is the role thread pool?

Thread pool function is to limit the number of execution threads in the system.

1, to improve the efficiency created a certain number of threads in the pool, and so need to use the time to get from a pool this time than needed to create a thread object much faster.

2, to facilitate the management can write a thread pool thread management code for the same pool of management, for example, there is the program to create 100 threads at startup, whenever there is a request to allocate a thread to work, if there happens to concurrent 101 requests that the extra which a request can be queued, create a thread to avoid endless cause the system to crash.

19. talk about several common thread pool and use scenarios?

1, newSingleThreadExecutorcreate a single-threaded thread pool, use it only to perform the task only worker threads to ensure that all tasks are performed in a specified order (FIFO, LIFO, priorities).

2, newFixedThreadPoolcreate a fixed-size thread pool, you can control the maximum number of concurrent threads, excess threads will wait in the queue.

3, newCachedThreadPoolcreate a cache thread pool, thread pool longer than if treatment needs, the flexibility to reclaim idle thread, if not recyclable, the new thread.

4, newScheduledThreadPoolcreate a fixed-length thread pool to support regular and periodic task execution.

20. Several important parameters of threads in the pool?

corePoolSizeIs the core number of threads in the pool, these core thread, just in time to no avail, it will not be recovered

maximumPoolSizeMaximum number of threads in the thread pool that can hold

keepAliveTimeIs the time of the longest thread pool in addition to other than the core thread can be retained, because in the thread pool, in addition to the core thread can not be cleared even in the absence of the task, the rest are all survival time, meaning that non-core thread can be reserved longest idle time. util, It is to calculate the time of a unit.

workQueueIs waiting queue, the task can be stored in the task queue waiting to be executed, the execution is FIFIO principle (FIFO).

threadFactory, It is to create a thread thread factory.

handler, Is a denial strategy, we can after a task full, refused to perform certain tasks.

21. refused to talk about strategies thread pool?

When the request came ongoing task, and the system processing, but this time they came, we need to take the policy is a denial of service. RejectedExecutionHandler interface provides an opportunity to reject the ways to customize job processing. In ThreadPoolExecutor already contains four processing strategies.

  • AbortPolicy Strategy: The strategy will direct throw, prevent the system from working properly.

  • CallerRunsPolicy strategy: as long as the thread pool is not closed, the policy directly in the caller's thread, run the current task is discarded.

  • DiscardOleddestPolicy strategy: This strategy will discard the oldest one request, that is the task to be executed, and try to submit the current job again.

  • DiscardPolicy strategy: the strategy silently discard task can not be processed without any treatment.

In addition to four kinds of JDK provided by default deny policy, we can refuse strategy according to their business needs to customize, customized approach is simple, direct implementation of RejectedExecutionHandlerthe interface can be.

22. execute and submit the difference?

Our mission is to execute the method used, in addition to the execute method, there is a submit method can also perform the task we have submitted.

These two methods What difference does it make? Respectively, for under what scenario? We do a simple analysis.

  • execute applied to less concerned about the return value of the scene, just to throw a thread pool thread to execute it.

  • submit method is suitable for scenarios need to focus on the return value

23. The five kinds of thread pool usage scenarios?

  • newSingleThreadExecutor: a single-threaded thread pool that can be used to ensure the required scenario execution of the order, and only one execution thread.

  • newFixedThreadPool: a fixed-size thread pool may be used in case of the known concurrent pressure limit of the number of threads do.

  • newCachedThreadPool: a thread pool can expand infinitely more suitable for processing execution time is relatively small task.

  • newScheduledThreadPool: can delay start, time to start the thread pool for the scene needs more background thread to perform periodic task.

  • newWorkStealingPool: a task queue with multiple thread pool, you can reduce the number of connections currently available to create a cpu number of threads to execute in parallel.

24. How do you close the thread pool? Choose the number of initialization thread pool thread?

Close the thread pool can call shutdownNow and two methods to achieve shutdown

shutdownNow: on the task being performed all the issued interrupt (), stop execution of the task has not yet started execution of the abolition of all, and not return to the task list to start.

shutdown: When we call the shutdown, the thread pool will no longer accept new tasks, but will not be forced to terminate has been submitted or task being performed.

If the task is IO intensive, the number of threads in general need to set up more than twice the number of CPU, in order to make full use of CPU resources.

If the task is CPU-intensive, the number of threads generally only need to set the number of CPU 1 can add more threads can only increase the number of context switches, CPU utilization can not be increased.

These are just a basic idea, later if you really need precise control, on-line or need to observe the number of threads in the pool of threads with the queue to be.

25. What kinds of thread pool has a work queue?

1、ArrayBlockingQueue

Is based on a configuration of the array bounded blocking queue This queue FIFO (first in first out) principle sort elements.

2, LinkedBlockingQueuebased on the blocking list queue structure, This queue FIFO (First In First Out) collating element, usually higher than a certain ArrayBlockingQueue. Static factory method Executors.newFixedThreadPool () uses this queue

3、SynchronousQueue

A blocking queue element is not stored. Each insert operation must wait until another thread calls the removal operation, or insert operation has been in a blocked state, throughput is usually higher than LinkedBlockingQueue, static factory method Executors.newCachedThreadPool use this queue.

4、PriorityBlockingQueue

A priority queue has unlimited obstruction.

recommend

Manufacturers written content collection (with detailed analytical) continuously updated in ....

ProcessOn aggregation platform is an online mapping tool -

The end of the sentence

Welcome attention to personal micro-channel public number: Coder programming welcome attention Coder programming public numbers, the main share data structures and algorithms, Java-related knowledge, the framework of knowledge and principle, Spring family bucket, micro-services project combat, DevOps practices of the road, one day Internet giant pen articles or interview questions and PMP project management knowledge. More exciting content is on the way - built a qq group: 315 211 365, we welcome into the group exchange study together. Thank you! Can also be introduced to the side of a friend in need.

Articles included to Github: github.com/CoderMerlin... Gitee: gitee.com/573059382/c... welcome attention and star ~

Micro-channel public number

Guess you like

Origin juejin.im/post/5dd39e1be51d453fd16b196c