Selected Java Concurrency Interview Questions

640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1

1. What is a thread?

Thread is the smallest unit that the operating system can perform operation scheduling. It is included in the process and is the actual operation unit in the process. Programmers can use it for multiprocessor programming, and you can use multithreading to speed up computationally intensive tasks. For example, if it takes 100 milliseconds for one thread to complete a task, it only takes 10 milliseconds to complete the task with ten threads.


2. What is the difference between a thread and a process?

Threads are a subset of processes, and a process can have many threads, each executing a different task in parallel. Different processes use different memory spaces, and all threads share the same memory space. Each thread has a separate stack memory for storing local data.


3. How to implement threads in Java?

Two ways: an instance of the java.lang.Thread class is a thread but it needs to call the java.lang.Runnable interface to execute. Since the thread class itself is the Runnable interface called, you can inherit the java.lang.Thread class or call it directly Runnable interface to override the run() method to implement threads.


4. What is the difference between the Java keywords volatile and synchronized?

1,volatile

The variable it modifies does not retain a copy and directly accesses the one in main memory.

In the Java memory model, there is main memory, and each thread also has its own memory (such as registers). For performance, a thread keeps a copy of the variable to be accessed in its own memory. In this way, the value of the same variable in the memory of one thread may be inconsistent with the value in the memory of another thread or the value in the main memory at a certain moment. A variable declared as volatile means that the variable can be modified by other threads at any time, so it cannot be cached in thread memory.

2,synchronized

When it is used to decorate a method or a code block, it can ensure that at most one thread executes the code at the same time.

1. When two concurrent threads access the synchronized (this) synchronized code block in the same object object, only one thread can be executed at a time. Another thread must wait for the current thread to finish executing the code block before executing the code block.

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

Third, it is especially critical that when a thread accesses a synchronized (this) synchronized code block of an object, other threads' access to all other synchronized (this) synchronized code blocks in the object will be blocked.

Fourth, when a thread accesses a synchronized (this) synchronization code block of an object, it acquires the object lock of this object. As a result, other threads' access to all synchronized parts of the object object is temporarily blocked.

5. The above rules are also applicable to other object locks.


5. What are the different thread life cycles?

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


6. What is your understanding of thread priority?

Each thread has a priority. Generally speaking, high-priority threads will have priority at runtime, but this depends on the implementation of thread scheduling, which is OS dependent. We can define the priority of threads, but this does not guarantee that higher priority threads will execute before lower priority threads. Thread priority is an int variable (from 1-10), with 1 being the lowest priority and 10 being the highest.


7. What is Deadlock? How to analyze and avoid deadlock?

A deadlock is a situation where two or more threads are permanently blocked, which requires at least two or more threads and two or more resources.

To analyze the deadlock, we need to look at the thread dump of the Java application. We need to find out which threads are in state BLOCKED and what resources they are waiting for. Each resource has a unique id, and with this id we can find out which threads already own its object lock.

Avoiding nested locks, using locks only where needed, and avoiding waiting indefinitely are common ways to avoid deadlocks.


8. What is thread safety? Is Vector a thread safe class?

如果你的代码所在的进程中有多个线程在同时运行,而这些线程可能会同时运行这段代码。如果每次运行结果和单线程运行的结果是一样的,而且其他的变量的值也和预期的是一样的,就是线程安全的。一个线程安全的计数器类的同一个实例对象在被多个线程使用的情况下也不会出现计算失误。很显然你可以将集合类分成两组,线程安全和非线程安全的。Vector 是用同步方法来实现线程安全的, 而和它相似的ArrayList不是线程安全的。


9,Java中如何停止一个线程?

Java提供了很丰富的API但没有为停止线程提供API。JDK 1.0本来有一些像stop(), suspend() 和 resume()的控制方法但是由于潜在的死锁威胁因此在后续的JDK版本中他们被弃用了,之后Java API的设计者就没有提供一个兼容且线程安全的方法来停止一个线程。当run() 或者 call() 方法执行完的时候线程会自动结束,如果要手动结束一个线程,你可以用volatile 布尔变量来退出run()方法的循环或者是取消任务来中断线程


10,什么是ThreadLocal?

ThreadLocal用于创建线程的本地变量,我们知道一个对象的所有线程会共享它的全局变量,所以这些变量不是线程安全的,我们可以使用同步技术。但是当我们不想使用同步的时候,我们可以选择ThreadLocal变量。

每个线程都会拥有他们自己的Thread变量,它们可以使用get()set()方法去获取他们的默认值或者在线程内部改变他们的值。ThreadLocal实例通常是希望它们同线程状态关联起来是private static属性。


11,Sleep()、suspend()和wait()之间有什么区别?

Thread.sleep()使当前线程在指定的时间处于“非运行”(Not Runnable)状态。线程一直持有对象的监视器。比如一个线程当前在一个同步块或同步方法中,其它线程不能进入该块或方法中。如果另一线程调用了interrupt()方法,它将唤醒那个“睡眠的”线程。

注意:sleep()是一个静态方法。这意味着只对当前线程有效,一个常见的错误是调用t.sleep(),(这里的t是一个不同于当前线程的线程)。即便是执行t.sleep(),也是当前线程进入睡眠,而不是t线程。t.suspend()是过时的方法,使用suspend()导致线程进入停滞状态,该线程会一直持有对象的监视器,suspend()容易引起死锁问题。

object.wait()使当前线程出于“不可运行”状态,和sleep()不同的是wait是object的方法而不是thread。调用object.wait()时,线程先要获取这个对象的对象锁,当前线程必须在锁对象保持同步,把当前线程添加到等待队列中,随后另一线程可以同步同一个对象锁来调用object.notify(),这样将唤醒原来等待中的线程,然后释放该锁。基本上wait()/notify()与sleep()/interrupt()类似,只是前者需要获取对象锁。


12,什么是线程饿死,什么是活锁?

当所有线程阻塞,或者由于需要的资源无效而不能处理,不存在非阻塞线程使资源可用。JavaAPI中线程活锁可能发生在以下情形:

1,当所有线程在程序中执行Object.wait(0),参数为0的wait方法。程序将发生活锁直到在相应的对象上有线程调用Object.notify()或者Object.notifyAll()。

2,当所有线程卡在无限循环中。


13,什么是Java Timer类?如何创建一个有特定时间间隔的任务?

java.util.Timer是一个工具类,可以用于安排一个线程在未来的某个特定时间执行。Timer类可以用安排一次性任务或者周期任务。

java.util.TimerTask是一个实现了Runnable接口的抽象类,我们需要去继承这个类来创建我们自己的定时任务并使用Timer去安排它的执行。


14,Java中的同步集合与并发集合有什么区别?

同步集合与并发集合都为多线程和并发提供了合适的线程安全的集合,不过并发集合的可扩展性更高。

在Java1.5之前程序员们只有同步集合来用且在多线程并发的时候会导致争用,阻碍了系统的扩展性。

Java5介绍了并发集合像ConcurrentHashMap,不仅提供线程安全还用锁分离和 内部分区等现代技术提高了可扩展性。


15,同步方法和同步块,哪个是更好的选择?

同步块是更好的选择,因为它不会锁住整个对象(当然你也可以让它锁住整个对象)。同步方法会锁住整个对象,哪怕这个类中有多个不相关联的同步块,这通常会导致他们停止执行并需要等待获得这个对象上的锁。


16,什么是线程池? 为什么要使用它?

创建线程要花费昂贵的资源和时间,如果任务来了才创建线程那么响应时间会变长,而且一个进程能创建的线程数有限。

为了避免这些问题,在程序启动的时候就创建若干线程来响应处理,它们被称为线程池,里面的线程叫工作线程。

从JDK1.5开始,Java API提供了Executor框架让你可以创建不同的线程池。比如单线程池,每次处理一个任务;数目固定的线程池或者是缓存线程池(一个适合很多生存期短的任务的程序的可扩展线程池)。


17,Java中invokeAndWait 和 invokeLater有什么区别?

这两个方法是Swing API 提供给Java开发者用来从当前线程而不是事件派发线程更新GUI组件用的。InvokeAndWait()同步更新GUI组件,比如一个进度条,一旦进度更新了,进度条也要做出相应改变。如果进度被多个线程跟踪,那么就调用invokeAndWait()方法请求事件派发线程对组件进行相应更新。而invokeLater()方法是异步调用更新组件的。


18,多线程中的忙循环是什么?

忙循环就是程序员用循环让一个线程等待,不像传统方法wait(), sleep() 或 yield() 它们都放弃了CPU控制,而忙循环不会放弃CPU,它就是在运行一个空循环。这么做的目的是为了保留CPU缓存。

在多核系统中,一个等待线程醒来的时候可能会在另一个内核运行,这样会重建缓存。为了避免重建缓存和减少等待重建的时间就可以使用它了。


19,Java内存模型是什么?

Java内存模型规定和指引Java程序在不同的内存架构、CPU和操作系统间有确定性地行为。它在多线程的情况下尤其重要。Java内存模型对一个线程所做的变动能被其它线程可见提供了保证,它们之间是先行发生关系。这个关系定义了一些规则让程序员在并发编程时思路更清晰。比如,先行发生关系确保了:

线程内的代码能够按先后顺序执行,这被称为程序次序规则。

对于同一个锁,一个解锁操作一定要发生在时间上后发生的另一个锁定操作之前,也叫做管程锁定规则。

前一个对volatile的写操作在后一个volatile的读操作之前,也叫volatile变量规则。

一个线程内的任何操作必需在这个线程的start()调用之后,也叫作线程启动规则。

一个线程的所有操作都会在线程终止之前,线程终止规则。

一个对象的终结操作必需在这个对象构造完成之后,也叫对象终结规则。

可传递性

更多介绍可以移步并发编程网:

(深入理解java内存模型系列文章:http://ifeve.com/java-memory-model-0)


20,Java中interrupted 和isInterruptedd方法的区别?

interrupted() 和 isInterrupted()的主要区别是前者会将中断状态清除而后者不会。Java多线程的中断机制是用内部标识来实现的,调用Thread.interrupt()来中断一个线程就会设置中断标识为true。当中断线程调用静态方法Thread.interrupted()来检查中断状态时,中断状态会被清零。

非静态方法isInterrupted()用来查询其它线程的中断状态且不会改变中断状态标识。简单的说就是任何抛出InterruptedException异常的方法都会将中断状态清零。无论如何,一个线程的中断状态都有可能被其它线程调用中断来改变。


21,Java中的同步集合与并发集合有什么区别?

同步集合与并发集合都为多线程和并发提供了合适的线程安全的集合,不过并发集合的可扩展性更高。在Java1.5之前程序员们只有同步集合来用且在多线程并发的时候会导致争用,阻碍了系统的扩展性。Java5介绍了并发集合像ConcurrentHashMap,不仅提供线程安全还用锁分离和内部分区等现代技术提高了可扩展性。

不管是同步集合还是并发集合他们都支持线程安全,他们之间主要的区别体现在性能和可扩展性,还有他们如何实现的线程安全上。

同步HashMap, Hashtable, HashSet, Vector, ArrayList 相比他们并发的实现(ConcurrentHashMap, CopyOnWriteArrayList, CopyOnWriteHashSet)会慢得多。造成如此慢的主要原因是锁, 同步集合会把整个Map或List锁起来,而并发集合不会。并发集合实现线程安全是通过使用先进的和成熟的技术像锁剥离。

比如ConcurrentHashMap 会把整个Map 划分成几个片段,只对相关的几个片段上锁,同时允许多线程访问其他未上锁的片段。

同样的,CopyOnWriteArrayList 允许多个线程以非同步的方式读,当有线程写的时候它会将整个List复制一个副本给它。

如果在读多写少这种对并发集合有利的条件下使用并发集合,这会比使用同步集合更具有可伸缩性。


22,什么是线程池? 为什么要使用它?

创建线程要花费昂贵的资源和时间,如果任务来了才创建线程那么响应时间会变长,而且一个进程能创建的线程数有限。为了避免这些问题,在程序启动的时候就创建若干线程来响应处理,它们被称为线程池,里面的线程叫工作线程。从JDK1.5开始,Java API提供了Executor框架让你可以创建不同的线程池。比如单线程池,每次处理一个任务;数目固定的线程池或者是缓存线程池(一个适合很多生存期短的任务的程序的可扩展线程池)

线程池的作用,就是在调用线程的时候初始化一定数量的线程,有线程过来的时候,先检测初始化的线程还有空的没有,没有就再看当前运行中的线程数是不是已经达到了最大数,如果没有,就新分配一个线程去处理。

就像餐馆中吃饭一样,从里面叫一个服务员出来;但如果已经达到了最大数,就相当于服务员已经用尽了,那没得办法,另外的线程就只有等了,直到有新的“服务员”为止。

线程池的优点就是可以管理线程,有一个高度中枢,这样程序才不会乱,保证系统不会因为大量的并发而因为资源不足挂掉。


23,Java中活锁和死锁有什么区别?

活锁:一个线程通常会有会响应其他线程的活动。如果其他线程也会响应另一个线程的活动,那么就有可能发生活锁。同死锁一样,发生活锁的线程无法继续执行。然而线程并没有阻塞——他们在忙于响应对方无法恢复工作。这就相当于两个在走廊相遇的人:甲向他自己的左边靠想让乙过去,而乙向他的右边靠想让甲过去。可见他们阻塞了对方。甲向他的右边靠,而乙向他的左边靠,他们还是阻塞了对方。

死锁:两个或更多线程阻塞着等待其它处于死锁状态的线程所持有的锁。死锁通常发生在多个线程同时但以不同的顺序请求同一组锁的时候,死锁会让你的程序挂起无法完成任务。


24,如何避免死锁?

死锁的发生必须满足以下四个条件:

互斥条件:一个资源每次只能被一个进程使用。

请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放。

不剥夺条件:进程已获得的资源,在末使用完之前,不能强行剥夺。

循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系。

三种用于避免死锁的技术:

加锁顺序(线程按照一定的顺序加锁)

加锁时限(线程尝试获取锁的时候加上一定的时限,超过时限则放弃对该锁的请求,并释放自己占有的锁)

死锁检测

(死锁原因及如何避免更深理解移步:http://blog.csdn.net/ls5718/article/details/51896159)


25,notify()和notifyAll()有什么区别?

1,notify()和notifyAll()都是Object对象用于通知处在等待该对象的线程的方法。

2,void notify(): 唤醒一个正在等待该对象的线程。

3,void notifyAll(): 唤醒所有正在等待该对象的线程。

两者的最大区别在于:

notifyAll使所有原来在该对象上等待被notify的线程统统退出wait的状态,变成等待该对象上的锁,一旦该对象被解锁,他们就会去竞争。

notify他只是选择一个wait状态线程进行通知,并使它获得该对象上的锁,但不惊动其他同样在等待被该对象notify的线程们,当第一个线程运行完毕以后释放对象上的锁,此时如果该对象没有再次使用notify语句,即便该对象已经空闲,其他wait状态等待的线程由于没有得到该对象的通知,继续处在wait状态,直到这个对象发出一个notify或notifyAll,它们等待的是被notify或notifyAll,而不是锁。


26,什么是可重入锁(ReentrantLock)?

Java.util.concurrent.lock 中的 Lock 框架是锁定的一个抽象,它允许把锁定的实现作为Java 类,而不是作为语言的特性来实现。这就为Lock 的多种实现留下了空间,各种实现可能有不同的调度算法、性能特性或者锁定语义。 ReentrantLock 类实现了Lock ,它拥有与synchronized 相同的并发性和内存语义,但是添加了类似锁投票、定时锁等候和可中断锁等候的一些特性。此外,它还提供了在激烈争用情况下更佳的性能。(换句话说,当许多线程都想访问共享资源时,JVM可以花更少的时候来调度线程,把更多时间用在执行线程上。)

What does a Reentrant lock mean? In simple terms, it has an acquisition counter associated with the lock, if a thread that owns the lock acquires the lock again, the acquisition counter is incremented by 1, and the lock needs to be released twice before it is actually released. This mimics the semantics of synchronized; if the thread enters a synchronized block protected by a monitor already owned by the thread, the thread is allowed to proceed, and when the thread exits the second (or subsequent) synchronized block, the lock is not released, only the thread exits The lock is only released when it enters the first synchronized block protected by the monitor.


27. What application scenarios can the read-write lock be used for?

Read-write locks can be used in the scenario of "more reading and less writing". Read-write locks support concurrent execution of multiple read operations, and write operations can only be performed by one thread.

ReadWriteLock is optimized for relatively infrequent writes to a data structure, but multiple tasks reading the data structure frequently. ReadWriteLock allows you to have multiple readers at the same time, as long as none of them try to write. If the write lock is already held by another task, no reader can access it until the write lock is released.

The improvement of program performance by ReadWriteLock is mainly subject to the following factors:

1. The result of comparing the frequency of data being read and the frequency of being modified.

2. Time of reading and writing

3. How many threads are competing

4. Is it running on a multiprocessing machine?

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326946345&siteId=291194637