In 2020 Java multithreading and concurrent series of 22 high-frequency interview questions (and answers attached analytical mind map)

Foreword

Now no matter how large or small company, go to the interview will be asked to multi-threaded and concurrent programming knowledge, we interview when this knowledge be sure to reserve well in advance.

About multithreading and concurrency knowledge summed up a mind map, for everyone to share

v2-ff5061172a05e7f3b821b1f08b532a44_720w.jpeg

1, the multi-threaded Java There are several ways

(1) Thread class inheritance;

(2) implement Runnable;

(3) implement Callable interface to create Thread by thread FutureTask wrapper;

(4) use ExecutorService, Callable, Future have realized returns the result of a multi-threaded (that is, the use of ExecutorService three ways to manage the front).

2, how to stop a running thread

(1) the use of exit signs, the thread exits normally, that is, after the completion of the thread run method terminates.

(2) method using a stop forcibly terminated, but does not recommend this method, because the method stop and suspend and resume are the same as the expire.

(3) using the interrupt method interrupt thread.

class MyThread extends Thread {
	volatile Boolean stop = false;
	public void run() {
		while (!stop) {
			System.out.println(getName() + " is running");
			try {
				sleep(1000);
			}
			catch (InterruptedException e) {
				System.out.println("week up from blcok...");
				stop = true;
				// modify shared variables exception handling code state
			}
		}
		System.out.println(getName() + " is exiting...");
	}}class InterruptThreadDemo3 {
	public static void main(String[] args) throws InterruptedException {
		MyThread m1 = new MyThread();
		System.out.println("Starting thread...");
		m1.start();
		Thread.sleep(3000);
		m1.interrupt();
		// blocked exits blocked state
		Thread.sleep(3000);
		// main thread to sleep three seconds in order to observe the situation m1 interrupted thread
		System.out.println("Stopping application...");
	}}

3, notify () and notifyAll () What is the difference?

notify could lead to a deadlock, but does not notifyAll

Any time only one thread can acquire the lock, which means that only one thread can run in synchronized code uses notifyall, can wake up all the threads in a wait state, it re-enters the lock contention of the queue, and notify only a wake.

wait () should be compatible with the use of the while loop should not be used if, be sure to check all the conditions before and after the wait () call. If not, you must call notify () wake up another thread to handle their own continuing wait () again until the conditions are met execution down.

notify () is optimized for a notifyAll (), but it has a very precise application scenarios, and requires proper use. Otherwise it might lead to a deadlock. WaitSet correct scene should be waiting in the same conditions, any of which can wake up the next matter of right, if awakened thread can not handle correctly, make sure to continue to notify () next thread, and return to their own needs WaitSet in.

4, sleep () and wait () What is the difference?

For the sleep () method, we first need to know which belongs Thread class. And wait () method, is part of the class Object

of.

sleep () method results in a program to suspend the specified time, so that the cpu of the other threads, but his remains were monitoring state, when the specified time is up will automatically resume operation. During the call to sleep () method, the thread will not release the object lock.

When the call to wait () method, the thread will give up the object lock, into the waiting for this object to wait for the lock pool, only after calling notify for this object () method of the thread before moving object lock pool ready to acquire the object lock into operation.

v2-0c087e22fca56285b587313521030a26_720w.png

5. What volatile is likely? Assures an orderly sex?

Once a shared variable (member variables of the class, the class of static member variables) after being declared volatile, then have the two semantics:

(1) to ensure visibility when different threads to this variable operation, that is a thread modifies the value of a variable, this new value to other thread is immediately visible, volatile keyword will force changes value write main memory immediately.

(2) prohibit instruction reordering.

Atomic operations are not volatile

What is the guarantee part of the orderly?

When the program is executed to read or write to a volatile variable, change in front of the entire operation certainly has, and the results are already visible on the back of the operation; operating behind it certainly has not been carried out;

x = 2; // statements 1y = 0; // statements 2flag = true; // statements 3x = 4; // statements 4y = -1; // statements 5

Since fl ag variables volatile variables, then the reordering process is performed in the instruction, it does not put the statement 3 statement 1, 2 in front of the statement, the statement does not speak into 3 statement 4, 5 behind the statement. But be careful sequence of statements 1 and 2 of the statement, sequential statements 4 and 5 of the statement is not any guarantee.

Volatile subject using double lock state is generally used and the amount of label Singleton pattern

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

start () method is used to start a new thread is created, and the start () internally calls the run () method, and this effect directly call run () method is not the same. 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.

7. Why wait, notify and notifyAll these methods are not thread inside the class?

JAVA obvious reason is to provide a lock object level rather than 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.

8. Why wait and notify methods to be invoked in a synchronized block?

(1) only if the calling thread has an exclusive lock on an object to be able to call the object's wait (), notify () and notifyAll () method.

(2) If you do not, your code will throw an exception IllegalMonitorStateException.

(3) Another reason is to avoid race conditions between the wait and notify.

wait () method forces the current thread releases the object lock. This means that before calling an object's wait () method, the current thread must have obtained a lock of the object. Therefore, before calling thread must wait () method of the object in the synchronization method of an object or synchronized block of code.

Before calling the object's notify () and notifyAll () method, the calling thread must have been a lock for the object. Thus, must notify call to the object () or notifyAll () method in the synchronization method of an object or a synchronization code blocks.

The reason to call wait () method is usually the calling thread wish to continue after a particular state (or variable) is set. The reason to call notify () or notifyAll () method is usually the calling thread want to tell others waiting thread: "special status has been set." This state, as inter-thread communication channel, it must be a shared state variable (or variables).

9, the difference in Java interrupted and isInterruptedd methods?

interrupted () and isInterrupted () The main difference between the former and the latter will not interrupt status clear. Java multi-threaded interrupt mechanism is used to achieve internal identification, call Thread.interrupt () to interrupt a thread will set the interrupt flag to true. When the interrupt thread calls the static method Thread.interrupted () to check the status of interrupt, the interrupt status is cleared. Rather than the static method isInterrupted () to query the status interrupt other threads and interrupt status will not change the logo. Simply means that any method will throw an exception InterruptedException interrupt status is cleared. In any case, there is a thread's interrupt status is likely to be called by other thread interrupts to change.

10, Java and in synchronized ReentrantLock What is the difference?

Similarity:

Both synchronous mode there are many similarities, they are locked synchronous mode, and are blocking synchronization, which means that if a thread when the object lock to get into the sync block access to the other sync blocks the cost of blocked threads must wait outside in sync blocks, while blocking threading and wake-up is relatively high.

the difference:

The biggest difference between these two methods is to Synchronized, it is the keyword java language, is the native syntax level mutual exclusion is required to achieve jvm. And it is ReentrantLock level API provided mutex after 1.5 JDK, requires lock () and unlock () method with the try / fi nally block of statements to complete.

Synchronized been to compile, will form the monitorenter and monitorexit instructions before and after the two-byte code sync blocks, respectively. In the implementation of monitorenter instruction, we must first try to obtain the object lock. If the object is not locked, or the current thread already has the object lock, the lock calculator plus 1, appropriate, in the implementation of monitorexit instruction will lock calculator to minus 1, when the calculator is 0:00, lock He was released. If the lock fails to obtain the object that the current thread will block until the object lock is released by another thread so far.

Since ReentrantLock a mutex is available under the java.util.concurrent package, compared to Synchronized, ReentrantLock class provides some advanced features, mainly in the following three:

(1) wait can be interrupted when the thread holding the lock release for long periods of waiting threads can choose to give up waiting, which is equivalent to the situation Synchronized it can avoid deadlock.

(2) fair locks, multiple threads waiting for the same lock, the lock must be obtained in accordance with the application lock chronological order, Synchronized lock unfair lock, ReentrantLock default constructor is created unfair lock can be set via the parameter true fair lock, but the lock fair performance performance is not very good.

(3) binding a plurality of lock condition, the object can be bound to a ReentrantLock objects simultaneously.

v2-68d41e0126eb04a454a9252ebc8dd613_720w.png

11, there are three threads T1, T2, T3, how to ensure the implementation of the order?

There are several ways in multiple threads thread to perform a specific order, you can start another thread in a thread with a join () method of the Thread class, another thread to complete the thread continues. In order to ensure an orderly three threads you should first start last (T3 call T2, T2 call T1), so it will be completed T1 and T3 finalized.

In fact the first three start thread which both a row, because each thread in the method run by the method of defining the order of execution join three threads.

public class JoinTest2 {
	// 1. There are T1, T2, T3 three threads, how do you ensure T2 after the implementation of execution in T1, T3 after the implementation of execution in T2
	public static void main(String[] args) {
		final Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println("t1");
			}
		}
		);
		@Override
		public void run() {
			try {
				// references t1 thread, the thread executing the waiting t1
				t1.join();
			}
			catch (InterruptedException e) {
				e.printStackTrace ();
			}
			System.out.println("t2");
		}
	}
	);
	Thread t3 = new Thread(new Runnable() {
		@Override
		public void run() {
			try {
				// references t2 thread, the thread executing the waiting t2
				t2.join();
			}
			catch (InterruptedException e) {
				e.printStackTrace ();
			}
			System.out.println("t3");
		}
	}
	);
	t3.start();
	// Here boot sequence can be any three threads, you can try next!
	t2.start();
	t1.start();}}

12, SynchronizedMap and ConcurrentHashMap What is the difference?

SynchronizedMap () and Hashtable, as implemented on all methods when calling the map, the entire map are synchronized. The implementation of ConcurrentHashMap but more precise, its map of all buckets added locks. So long as there is a thread to access the map, other threads can not enter the map, and if one thread accessing ConcurrentHashMap a barrel, other threads can still perform certain operations on the map.

So, ConcurrentHashMap in performance and safety, significantly higher than Collections.synchronizedMap () is more advantageous. At the same time, synchronous operation to precisely control the bucket, so that even when traversing the map, if another thread attempts to map data modification, it will not throw ConcurrentModi fi cationException.

13. What is thread-safe

That thread-safe multi-threaded access the same code, does not produce indeterminate results.

In a multithreaded environment, when each thread does not share data that are private (private) members, then it must be thread-safe. However, this situation is rare, need to share data, in most cases, when it is necessary for the proper synchronization control.

Thread safety generally involve synchronized, it is a piece of code at the same time only one thread to manipulate results otherwise can generate an intermediate process preformed.

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 each run ArrayList is not thread safe.

14, yield method of the Thread class in what role?

Yield method to pause the currently executing thread object, let the other have the same priority thread. It is a static method and only guarantee the current thread can not give up CPU usage to ensure that other threads will be able to take up the CPU, execute yield () thread is likely to be executed immediately after entering the suspended state.

15. What is the difference Java threads in the pool submit () and execute () method?

Both methods can be submitted to the thread pool task, return type execute () method is void, it is defined in the Executor interface, and submit () method returns an object held by Future calculation results, which is defined in ExecutorService interface, it extends the Executor interface, like the other thread pool ThreadPoolExecutor and ScheduledThreadPoolExecutor have these methods.

16, to talk about their own understanding of the synchronized keyword

The solution is synchronized keyword to access resources between multiple threads synchronization, synchronized keyword can be guaranteed by its modified method or block of code at any time, only one thread of execution.

Further, in the Java earlier versions, the synchronized heavyweight lock belongs, inefficient, since the monitor lock (monitor) is dependent on the underlying operating system to achieve Mutex Lock, Java threads are mapped to the operating system's native threads Up. To wake up a thread or suspend, the operating system needs to help complete, the need to convert from user mode to kernel mode when switching between threads operating system implementation, the transition between a state requires a relatively long time, time cost relatively high, which is why early synchronized low efficiency reasons. Fortunately, after Java 6 Java JVM-level official from the larger synchronized optimization, so now synchronized lock efficiency is optimized quite well. JDK1.6 lock achieved introduced a number of optimization, such as spin lock spin lock adaptability, to eliminate the lock, the lock roughening biased locking, lightweight and other techniques to reduce lock overhead lock operations.

17, to talk about how he is using the synchronized keyword, used the synchronized keyword use in three main projects:

(1) Modified example of the method : the lock acting on the current object instance, before entering the synchronization code to obtain the current lock object instance

(2) modify the static method : that is to lock the current class, will apply to all object instances of the class, because static members do not belong to any instance of an object, the class members (static indicates that this is a static resource class, regardless of how many new objects, only one). So if a thread A non-static synchronized method calls an instance of an object, and the thread B needs to call this static synchronized method belongs to the class of the object instance, is allowed, mutual exclusion will not happen, because access static synchronized method lock is occupied the current class locks, access to non-static synchronized method lock is occupied by the current instance of the object lock.

(3) modifying code blocks : the specified lock object, to lock a given object, in the synchronization code library to obtain a lock prior to a given object.

Summary : synchronized static keyword added to a static method and synchronized (class) is the code block is locked to the class Class. Examples of the synchronized keyword added to the object instance is locked. Try not to use synchronized (String a) because the JVM, the string constant pool has a cache function!

18. 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 each run

The results rows and single-threaded operating results are the same, and also the values ​​of other variables and expectations are the same, that is thread-safe.

19, the role of the volatile keyword?

Once a modified volatile shared variables (member variables of the class, the class of static member variables), then have the two languages

Yi:

(1) to ensure visibility when different threads to this variable operation, that is a thread modifies the value of a variable, this new value to other thread is immediately visible.

(2) prohibit instruction reordering.

(3) volatile nature is telling jvm current variable values ​​in register (working memory) is uncertain, needs to be read from the main memory; synchronized current variable is locked, only the current thread can access the variables, other threads He blocked live.

(4) volatile level can only be used in a variable; the synchronized variables can be used in the methods, and the class level.

(5) volatile visibility can be achieved only modify variables, does not guarantee atomicity; it is guaranteed that modify the synchronized visibility and atomic variables.

(6) volatile will not cause obstruction thread; synchronized may cause obstruction thread.

(7) not labeled volatile variable optimizing compiler; mark may be synchronized variable optimizing compiler.

v2-a2307d8f90ab3adac9c28fd2f2b0c37b_720w.png

20. What common thread pool?

(1) newSingleThreadExecutor: create a thread pool of single-threaded, this thread pool to ensure that the order of execution of all tasks presented to the order of tasks.

(2) newFixedThreadPool: to create a fixed-size thread pool, each commit a task to create a thread, until the thread pool thread to reach the maximum size.

(3) newCachedThreadPool: Creating a cached thread pool, this thread pool do not restrict the size of the thread pool, thread pool thread maximum size depends entirely on the size of the operating system (or JVM) that can be created.

(4) newScheduledThreadPool: Create an unlimited size of the thread pool, thread pool to support this demand as well as the timing of periodic tasks.

(5) newSingleThreadExecutor: create a thread pool of single-threaded. This thread pool to support the timing and the need to perform tasks periodically.

21, briefly your understanding of the thread pool

(If you ask the question, you can expand the thread pool How to talk about the benefits of the thread pool, thread pool startup policy) rational use of the thread pool can bring three benefits.

(1) reduce resource consumption. By reusing the thread has been created to reduce thread creation and destruction caused by consumption.

(2) increase the response speed. When the mission arrives, the task may not need to wait until the thread creation can be implemented immediately.

(3) increase the thread manageability. A thread is a scarce resource, if the unlimited creation, not only consumes system resources, but also reduce the stability of the system, using a thread pool can be unified distribution, tuning and monitoring.

22, Java program is how to implement it

Our daily work use development tools (IntelliJ IDEA or Eclipse, etc.) can easily debug a program, or by packing tool to project packaged into jar or bag war package, and so on into the Tomcat Web container to be a normal operation

(1) code is first compiled into Java byte code, i.e. the type of .java files compiled into .class file type. Substantially execution process of the process: Java source code -> lexical analyzer -> parser -> Semantic Analyzer -> character code generator -> ultimately generate byte code, any failure will cause the node to perform a compilation failure ;

(2) to place the class files to the Java virtual machine, the virtual machine usually refers to Oracle's own official Hotspot JVM;

(3) Java virtual machine class loader (Class Loader) loaded class files;

(4) After completion of the class loader, bytecode will efficacy, efficiency bytecode interpreter would then JVM byte code into machine code by translating test referred to the operating system. But not all of the code is interpreted, JVM optimized to do this, for example, to Hotspot virtual machine, it itself provides JIT (Just In Time) is what we usually refer to the dynamic compiler, it can runtime code is compiled to machine code hot spots, this time bytecode compiler implementation becomes. Java program flowchart executed as follows:

v2-9a650ff4fae65b471efcb741a3138c5b_720w.jpeg

At last

Welcome to public concern number: Programmer Herd, receive first-tier manufacturers Java interview questions summary + knowledge points learning Mind + a 300 Java core knowledge pdf document summary!

When the content of these materials are the interview the interviewer will ask knowledge points, chapter points, including a lot of knowledge, including basic knowledge, Java collections, JVM, multi-threaded, spring principle, micro-services, Netty and RPC, Kafka , diary, design patterns, Java algorithms, databases, Zookeeper, distributed caching, data structures, and so on.



Guess you like

Origin blog.51cto.com/14442094/2486138