Like most of the interviewer asked: multi-threading, thread concurrency face questions Comments (volatile + ThreadLocal + Sleep)

1. What is a thread?

A thread is the smallest unit of an operating system capable of operation schedule, which is included in the process, the actual operation of the unit process. Programmers can use it for multiprocessor programming, you can use multiple threads to accelerate compute-intensive tasks. For example, if a thread to complete a task to be 100 ms, then complete the task in just 10 milliseconds changed with ten threads.

2, threads and processes What is the difference?

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. Each thread has a separate stack memory used to store local data.

3, how to implement threads in Java?

In two ways: java.lang.Thread instance class is a thread but it needs to call java.lang.Runnable interface to execute, because the Thread class itself is called Runnable interface so you can inherit class or directly call java.lang.Thread Runnable interface to override the run () method to achieve the thread.

4, Java keyword volatile and synchronized action and the difference?

volatile

It modifies variable does not retain a copy, direct access to the main memory.
In the Java memory model, there are main memory, each thread has its own memory (for example, register). For performance, a thread will keep the copy of the variable to be accessed in their memory in. In such a moment, the value of a thread in the memory of the possible values of the same variable with another thread will appear in the memory or the main memory in the case of inconsistent values. A variable declared as volatile, it means that this variable is expected to be modified at any time other threads, so it can not be in the cache memory in the thread.

synchronized

When it is used, or a method of modifying a time code block, to ensure that at most one thread is executing code in the same period of the time.

  • First, 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.
  • Third, it 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.
  • Fourth, when a thread to access the object of a synchronized (this) sync block, it is obtained that the object of the object lock. As a result, other threads to access all objects of the object synchronization code sections have been temporarily blocked.
  • Fifth, the above rules apply equally to other object lock.

5. What are the different threads of the life cycle?

When we create a new thread in a Java program, its status is New. When we call the thread's start () method, the status is changed to Runnable. Thread scheduler allocates CPU time Runnable threads in the thread pool and tells their status is changed to Running. There are other thread state Waiting, Blocked and Dead.

6. What is your understanding of thread priority is?

Each thread has a priority, in general, high priority threads at runtime has priority, but this depends on the implementation of thread scheduling, and this implementation is operating system dependent (OS dependent). We can define the priority of the thread, but this does not guarantee high-priority thread will be executed before lower priority thread. Thread priority is an int variable (from 1-10), where 1 is the lowest priority and 10 is the highest priority.

7. What is a deadlock (Deadlock)? How to analyze and avoid deadlocks?

Deadlock refers to the case of two or more threads block forever, this situation needs to produce at least two or more than two threads and resources.
Analysis of deadlock, we need to see a thread dump Java applications. We need to find those BLOCKED state of threads and the resources they are waiting for. Each resource has a unique id, use the id we can find out which thread has its own object lock.
Avoid nested locks, lock only where needed and avoid waiting indefinitely is the usual way to avoid deadlock.

8. What is thread safe? Vector is a thread-safe class do?

If your code where the process has multiple threads running at the same time, and these threads may run this code at the same time. If the result of each run single-threaded operating results and the same, and also the values ​​of other variables and expectations are the same, that is thread-safe. A thread-safe counter the same instance of an object class will not miscalculations in the case of the use of multiple threads. Obviously you can collection class into two groups, thread-safe and non-thread-safe. Vector is synchronized methods to achieve thread-safe, but it and similar ArrayList is not thread safe.

9, how to stop a thread in Java?

Java API provides a very rich but did not provide an API to stop the thread. JDK 1.0 would have been something like stop (), suspend () and resume () method of control, but because of the potential threat and therefore a deadlock 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. Thread will automatically end when the run () or call () method to perform finished, if you want to end a thread manually, you can use volatile boolean variable to exit the run () method of recycling or cancel the task to interrupt thread

10. What is the ThreadLocal?

ThreadLocal thread is used to create a local variable, we know that an object of all the threads share its global variables, these variables are not thread-safe, we can use synchronous technology. But when we do not want to use sync, we can choose ThreadLocal variable.
Each thread will have their own Thread variable, they can use the get () set () methods to get their default value or change in value of their internal thread. ThreadLocal instance they usually want to associate with the thread state is private static properties.

11. What is the difference between Sleep (), suspend () and wait ()?

Thread.sleep () the current thread in the "non-operational" (Not Runnable) state at a specified time. Thread has been held object's monitor. In this example, a thread or a sync block synchronization method, other threads can not enter the block or method. If another thread calls interrupt () method, it will awaken the "sleeping" thread.
Note: sleep () is a static method. This means that only the current thread is active, a common mistake is to call t.sleep (), (t here is a thread different from the current thread). Even the execution t.sleep (), is the current thread goes to sleep, instead of t thread. t.suspend () method is obsolete, use suspend () causes the thread to enter a standstill, the thread will always hold an object's monitor, suspend () easily lead to deadlock.
object.wait () the current thread for "non-operational" state, and sleep () method is different is the wait object instead of thread. When you call object.wait (), the thread must first acquire the object lock the object, the current thread must be synchronized in lock object, add the current thread to wait in the queue, then another thread can be synchronized to the same object lock to call the object. notify (), this will awaken the original waiting thread, and then releases the lock. Substantially wait () / notify () and sleep () / interrupt () is similar except that it needs to acquire the object lock.

12. What is the thread starvation, what is livelocks?

When all threads are blocked, or due to invalid resource requirements and can not handle, non-blocking thread does not exist to make resources available. JavaAPI thread livelock may occur in the following situations:
when all threads of execution the Object.wait (0) in the program, the parameter is 0, the wait method. The program will send live lock until the thread calls Object.notify on the corresponding object () or Object.notifyAll ().
When all threads stuck in an infinite loop.

13. What is Java Timer class? How to create a task specific time interval?

java.util.Timer is a utility class that can be used to arrange a thread execution at a specific time in the future. Timer class can schedule one-time task or periodic task.
java.util.TimerTask is an abstract class implements Runnable interface, we need to extend this class to create our own timing and use the Timer task to arrange its execution.

14, a set of synchronous and concurrent collections in 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.
Before Java1.5 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.

15, synchronization method and synchronized block, which is the better choice?

Sync block is a better choice because it does not lock the entire object (of course you can make it to lock the entire object). Synchronization method will lock the entire object, even if this class has multiple sync blocks not associated with, which often leads them to stop execution and to wait to get a lock on this object.

16, what is the thread pool? Why use it?

To create a thread costly resources and time, if the task was to create a thread so the response time will be longer, and the limited number of threads a process can create.
To avoid these problems, when the program started several threads created to respond to treatment, they are called the thread pool, which threads called worker threads.
From the beginning JDK1.5, Java API provides the Executor framework allows you to create different thread pool. For example, a single thread pool, each dealing with a task; a fixed number of thread pool thread pool, or cache (for a much shorter survival task program scalable thread pool).

17, Java and invokeLater in invokeAndWait What is the difference?

These two methods are Java Swing API available to developers for dispatching thread updated with GUI components from the current thread instead of the event. InvokeAndWait () synchronization update GUI components, such as a progress bar, once progress updates, the progress bar should make the appropriate change. If the progress is tracked by multiple threads, then call invokeAndWait () method to request event-dispatching thread components updated accordingly. The invokeLater () method is called asynchronously updated component.

18, What are you doing multi-threading cycle is?

Busy cycle is the cycle so that a programmer with thread to wait, unlike traditional methods wait (), sleep () or yield () they have given up control of the CPU, and CPU busy cycle will not give up, it is running an empty cycle. The goal is to retain the CPU cache.
When the multi-core system, a waiting thread might wake up in another kernel is running, it will rebuild the cache. In order to avoid and reduce the waiting time to rebuild cache rebuild you can use it

Welcome to sweep under the Fanger Wei code plus java learning technology exchange group, with solid foundation, enhance self-worth



Guess you like

Origin juejin.im/post/5d3bfb17f265da1ba77cebe2