Java interviewers love to ask questions face multithreading and concurrent summary, brush a problem, more than peace of mind!

Multi-threaded Java Interview Questions

1 , What is the difference between processes and threads?

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. Java runtime environment is a single process contains different classes and programs. Threads can be called lightweight processes. Thread requires fewer resources to create and resides in the process, and the process can be shared resources.

2 , What are the benefits of multi-threaded programming is?

In a multithreaded program, concurrent execution of multiple threads is to improve the efficiency of the program, CPU will not need to wait for a thread to enter an idle state resources. Multiple threads shared heap memory (heap memory), so creating multiple threads to perform some tasks better than creating multiple processes. For example, Servlets better than CGI, because Servlets and CGI does not support multi-threading support.

3 , the user thread and thread guard what is the difference?

When we create a thread in a Java program, it is called a user thread. A thread is a daemon in the background and does not prevent the termination of the JVM thread. When there is no user threads running, JVM close the program and exit. A guardian of the child thread thread creation is still a daemon thread.

4 , How do we create a thread?

There are two ways to create threads: First, to achieve Runnable interface, and then it passed to the Thread constructor, create a Thread object; the second is the direct successor Thread class.

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 will provide Runnable allocate CPU time to threads in the pool and tells their status is changed to Running. There are other thread state Waiting, Blocked and Dead .

6 , can be called directly run Thread class () method it?

Of course you can, but if we call the Thread's run () method, its behavior will be the same as ordinary methods, in order to execute our code in a new thread, you must use Thread.start () method.

7 , how to make a running thread pause for some time?

We can use the Thread class Sleep () method thread to pause for some time. Note that this does not make the thread terminates, the thread once awakened from hibernation, the state of the thread will be changed to Runnable, and according to thread scheduling, it will be implemented.

8 , 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.

9 , what is the thread scheduler (Thread Scheduler) and time slicing (Time Slicing)?

Thread scheduler is an operating system service, which is responsible for the state of Runnable thread allocation of CPU time. Once we create a thread and start it, it will depend on the implementation of the implementation of the thread scheduler. Refers to the process time slice is the available CPU time assigned to an available thread Runnable. Allocates CPU time can thread priority or thread wait on. Thread scheduling is not controlled by the Java virtual machine, so the application to control it is a better choice (that is to say do not let your application depends on the priority of the thread).

10 , in the multi-thread, what is the context switch (context-switching)?

Context switch is to store and restore the CPU state process, so that it can be a thread of execution resumes from the interruption point. Context switching is an essential feature of multi-tasking operating systems and multi-threaded environments.

11 , how do you ensure that the main () method where the thread is a Java program ended last thread?

We can use the joint () method of the Thread class to ensure that all programs created by a thread before the end of main () method exits.

12 , how to communicate between threads?

When the threads can share resources, inter-thread communication is important to coordinate their means. Object class wait () \ notify () \ notifyAll () method may be used for communication between threads lock on the resource state. Click here to have more threads wait, notify and notifyAll about.

13 , why the method of communication threads wait (), notify () and notifyAll () is defined in the Object class?

Each object has a lock in Java (monitor, the monitor may be) and wait (), notify () method and the like waiting for a lock or notification monitor objects other threads available objects. Not available for any locks and synchronization objects used in the Java thread. This is why these methods are part of the Object class, and each class has a Java basic method for communication between threads

14 , why wait (), notify () and notifyAll () must be called synchronization method or a synchronized block?

When a thread needs to call the object's wait () method, the thread must have a lock on the object, then it will release the object lock and enters a wait state until another thread calls notify on this subject () method. Similarly, when a thread needs to call the object's notify () method, which will release the lock of the object, so that other thread waiting you can get the object lock. Since all of these methods require a thread holds a lock on the object, so it can only be achieved through synchronous, so they can only be called synchronization method or a synchronized block.

15 , why the Thread class sleep () and yield () method is static?

sleep (Thread class) and yield () method will be run on the thread that is currently being executed. So call these methods on other threads in a wait state is meaningless. This is why these methods are static. They can work in threads that are currently being executed, and to avoid mistakenly believe that programmers can call these methods in other non-running thread.

16 , how to ensure thread-safe?

There are many ways in Java to ensure thread safety - synchronized with atomic class (atomic concurrent classes), lock concurrency, use the volatile keyword, use the same class and thread-safe class.

17 , what is the role of volatile keyword in Java?

When we use the volatile keyword to modify variables, so the thread will directly read the variable and does not cache it. This ensures that the thread reads the variable is the same in memory is the same.

18 , 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.

19 , how to create a daemon thread?

Use setDaemon Thread class (true) method can set a thread as a daemon thread, you need to pay attention to is the need to call this method before calling the start () method, otherwise it will throw an exception IllegalThreadStateException.

20 , 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.

21 , what is the Thread Group? Why is it recommended?

ThreadGroup is a class, its purpose is to provide information about the thread group.

ThreadGroup API is relatively weak, it does not provide more functionality than Thread. It has two main functions: First, get a list of active thread group in the state of a thread; the second is to set up a thread uncaught exception handler (ncaught exception handler). But in the Thread class in Java 1.5 also adds setUncaughtExceptionHandler (UncaughtExceptionHandler eh) method, so ThreadGroup is outdated, not recommended for continued use.

t1.setUncaughtExceptionHandler(new UncaughtExceptionHandler(){

@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("exception occured:"+e.getMessage());
}
});

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.

22 , What is Java thread dump (Thread Dump), how to get it?

JVM thread dump is a list of active threads, it is very useful for analyzing system bottlenecks and deadlocks. There are many ways to get a thread dump - Using Profiler, Kill -3 command, jstack tools. I prefer jstack tool because it is easy to use and comes with the JDK. Because it is a terminal-based tool, so we can write some scripts to generate timing thread dump to be analyzed.

23 , 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.

24 , 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.

25 , what is the thread pool? How to create a Java thread pool?

A thread pool management a set of worker threads, but it also includes a queue waiting to be executed for the task of placing.

java.util.concurrent.Executors java.util.concurrent.Executor provides an implementation of the interface used to create the thread pool. ScheduledThreadPoolExecutor thread pool examples show examples of how to create and use the thread pool, or read on to learn how to create a periodic task.

Java Concurrency Interview Questions

1 , What is the atomic operation? Which atoms class (atomic classes) have in Java Concurrency API in?

Refers to an atomic operation is not otherwise affect the operation of the operation unit task. Atomic operations to avoid data inconsistency means to be in a multithreaded environment.

int++并不是一个原子操作,所以当一个线程读取它的值并加1时,另外一个线程有可能会读到之前的值,这就会引发错误。

为了解决这个问题,必须保证增加操作是原子的,在JDK1.5之前我们可以使用同步技术来做到这一点。到JDK1.5,java.util.concurrent.atomic包提供了int和long类型的装类,它们可以自动的保证对于他们的操作是原子的并且不需要使用同步。

2、Java Concurrency API中的Lock接口(Lock interface)是什么?对比同步它有什么优势?

Lock接口比同步方法和同步块提供了更具扩展性的锁操作。他们允许更灵活的结构,可以具有完全不同的性质,并且可以支持多个相关类的条件对象。

它的优势有:

  • 可以使锁更公平
  • 可以使线程在等待锁的时候响应中断
  • 可以让线程尝试获取锁,并在无法获取锁的时候立即返回或者等待一段时间
  • 可以在不同的范围,以不同的顺序获取和释放锁

3、什么是Executors框架?

Executor框架同java.util.concurrent.Executor 接口在Java 5中被引入。Executor框架是一个根据一组执行策略调用,调度,执行和控制的异步任务的框架。

无限制的创建线程会引起应用程序内存溢出。所以创建一个线程池是个更好的的解决方案,因为可以限制线程的数量并且可以回收再利用这些线程。利用Executors框架可以非常方便的创建一个线程池。

4、什么是阻塞队列?如何使用阻塞队列来实现生产者-消费者模型?

java.util.concurrent.BlockingQueue的特性是:当队列是空的时,从队列中获取或删除元素的操作将会被阻塞,或者当队列是满时,往队列里添加元素的操作会被阻塞。

阻塞队列不接受空值,当你尝试向队列中添加空值的时候,它会抛出NullPointerException。

阻塞队列的实现都是线程安全的,所有的查询方法都是原子的并且使用了内部锁或者其他形式的并发控制。

BlockingQueue 接口是java collections框架的一部分,它主要用于实现生产者-消费者问题。

5、什么是Callable和Future?

Java 5在concurrency包中引入了java.util.concurrent.Callable 接口,它和Runnable接口很相似,但它可以返回一个对象或者抛出一个异常。

Callable接口使用泛型去定义它的返回类型。Executors类提供了一些有用的方法去在线程池中执行Callable内的任务。由于Callable任务是并行的,我们必须等待它返回的结果。java.util.concurrent.Future对象为我们解决了这个问题。在线程池提交Callable任务后返回了一个Future对象,使用它我们可以知道Callable任务的状态和得到Callable返回的执行结果。Future提供了get()方法让我们可以等待Callable结束并获取它的执行结果。

6、什么是FutureTask?

FutureTask是Future的一个基础实现,我们可以将它同Executors使用处理异步任务。通常我们不需要使用FutureTask类,单当我们打算重写Future接口的一些方法并保持原来基础的实现是,它就变得非常有用。我们可以仅仅继承于它并重写我们需要的方法。

7、什么是并发容器的实现?

Java集合类都是快速失败的,这就意味着当集合被改变且一个线程在使用迭代器遍历集合的时候,迭代器的next()方法将抛出ConcurrentModificationException异常。

并发容器支持并发的遍历和并发的更新。

主要的类有ConcurrentHashMap, CopyOnWriteArrayList 和CopyOnWriteArraySet

8、Executors类是什么?

Executors为Executor,ExecutorService,ScheduledExecutorService,ThreadFactory和Callable类提供了一些工具方法。

Executors可以用于方便的创建线程池。

读者福利、完整面试题【含答案】Java核心笔记,Java架构面试专题整合800道(pdf文档)

免费获取Java学习笔记,面试,文档以及视频

Guess you like

Origin blog.csdn.net/woshinidadaye_/article/details/94558471