Typical Java thread interview questions 70

Source: Internet
Author: User
Tags constructor data structures finally block garbage collection semaphore sleep thread class volatile

The following are top questions related to Java threads. You can use them to prepare for the interview.

1) What is a thread?

A thread is the smallest unit that the operating system can schedule operations. It is included in the process and is the actual operating unit of the process. Programmers can program with multiple processors. You can use multiple threads to speed up computing-intensive tasks. For example, if a thread needs 100 milliseconds to complete a task, it takes 10 milliseconds to complete the task with 10 threads. Java provides excellent support for multithreading at the language layer, which is also a good selling point.

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

A thread is a subset of a process. A process can have multiple threads and each thread executes different tasks in parallel. Different processes use different memory spaces, and all threads share the same memory space. Do not mix it with stack memory. Each thread has a separate stack memory to store local data.

3) how to implement threads in Java?

There are two ways at the language level. Java. lang. an instance of the Thread class is a Thread, but it needs to call java. lang. run the Runnable interface. Because the thread class itself is the called Runnable interface, you can inherit java. lang. thread class or directly call the Runnable interface to override the run () method to implement the Thread.

4) using Runnable or Thread?

This problem is the follow-up of the above question. We all know that we can implement the Thread by inheriting the Thread class or calling the Runnable interface. The problem is, what is better? When should I use it? This is easy to answer. If you know that Java does not support multiple class inheritance, you can call multiple interfaces. Therefore, if you want to inherit other classes, it is better to call the Runnable interface.

6) What is the difference between the start () and run () methods in the Thread class?

This question is frequently asked, but it is still possible to distinguish the degree to which the interviewer understands the Java Thread model. The start () method is used to start the newly created thread, and the start () method is called internally, which is different from the effect of directly calling the run () method. When you call the run () method, it will only be called in the original thread. If no new thread starts, the start () method will start the new thread.

7) What is the difference between Runnable and Callable in Java?

Runnable and Callable both represent the tasks to be executed in different threads. Runnable has been available since JDK1.0, and Callable has been added in JDK1.5. The main difference between them is that the Callable call () method can return values and throw exceptions, while the Runnable run () method does not have these functions. Callable can return the Future object loaded with calculation results.

8) What is the difference between javasicbarrier and CountDownLatch in Java?

Both CyclicBarrier and CountDownLatch can be used to hold a group of threads waiting for other threads. Unlike CyclicBarrier, CountdownLatch cannot be used again.

9) What is the Java memory model?

The Java memory model specifies and guides Java programs to behave deterministic between different memory architectures, CPUs, and operating systems. It is particularly important in the case of multithreading. The changes made to a thread by the Java memory model can be visible to other threads, and the relationship between them is first-in-first-out. This relationship defines some rules to give programmers a clearer idea in concurrent programming. For example, the first link ensures that:

Code in a thread can be executed sequentially, which is called a program order rule.
For the same lock, one unlock operation must occur after the time before another lock operation, also known as a pipe lock rule.
The previous write operation on volatile is called the volatile variable rule before the read operation on the latter volatile.
Any operation in a thread must be called after start () of the thread, also known as the thread startup rule.
All operations of a thread will terminate the rule before the thread ends.
The end operation of an object must be called an object termination rule after the object is constructed.
Portability

I strongly recommend that you read chapter 16th of Java concurrent programming practices to better understand the Java memory model.

10) What is the volatile variable in Java?

Volatile is a special modifier that can only be used by member variables. When a Java concurrent program lacks a synchronization class, the operations of multithreading on member variables are transparent to other threads. The volatile variable ensures that the next read operation will occur after the previous write operation, which is the volatile variable rule of the previous question.

11) What is thread security? Is Vector a thread security class?

If multiple threads are running simultaneously in the process where your code is located, these threads may run the code at the same time. If the result of each running is the same as that of a single thread, and the value of other variables is the same as expected, it is thread-safe. When the same instance object of a thread-safe counter class is used by multiple threads, no calculation error occurs. Obviously, you can divide collection classes into two groups: thread-safe and non-thread-safe. Vector uses the synchronous method to implement thread security, and its similar ArrayList is not thread-safe.

12) What is a race condition in Java? For example.

Competing conditions may cause some bugs in the program concurrency. When multiple threads compete for some resources, a race condition will be generated. If the competition for the first program to be executed fails and is executed later, the whole program will have some uncertain bugs. This kind of bugs is hard to find and will repeat because of random competition between threads.

13) how to stop a thread in Java?

Java provides a wide range of APIs, but does not provide APIs for stopping threads. JDK 1.0 has some control methods like stop (), suspend (), and resume (). However, due to the potential deadlock threats, they are discarded in subsequent JDK versions, then, the Java API designer does not provide a compatible and thread-safe method to stop a thread. When the run () or call () method is executed, the thread ends automatically. To manually end a thread, you can use the volatile Boolean variable to exit run () method or cancel the task to interrupt the thread.

14) What if an exception occurs when a thread is running?

This is a very tricky Java interview I encountered during an interview. Simply put, if exceptions are not caught, the thread will stop running. Thread. UncaughtExceptionHandler is an embedded interface used to handle sudden Thread interruption caused by exceptions not captured. When an uncaptured exception causes Thread interruption, JVM uses the Thread. getUncaughtExceptionHandler () is used to query the thread's UncaughtExceptionHandler and pass the thread and exception as parameters to the handler's uncaughtException () method for processing.

15) how to share data between two threads?

You can use shared objects to achieve this purpose, or use a data structure that is concurrent like blocking a queue. In this tutorial Java inter-thread communication (involving sharing objects between two threads), the producer consumer model is implemented using the wait and consumer y methods.

16) What is the difference between policy and policyall in Java?

This is another issue of the drill-down, because multithreading can wait for a single monitoring lock, Java API designers provide some methods to notify them when the conditions change, but these methods are not fully implemented. The Y () method cannot wake up a specific thread, so it can be used only when a thread is waiting. Policyall () wakes up all threads and allows them to compete for the lock to ensure that at least one thread can continue to run.

17) why are wait, policy, and policyall methods not in the thread class?

This is a design-related issue. It examines the interviewer's views on existing systems and common but seemingly unreasonable things. When answering these questions, you need to explain why it makes sense to put these methods in the Object class, and why not put them in the Thread class. One obvious reason is that the lock provided by JAVA is at the object level rather than the thread level. Each object has a lock and is obtained through a thread. If the thread needs to wait for some locks, it makes sense to call the wait () method in the object. If the wait () method is defined in the Thread class, it is not obvious which lock the Thread is waiting. Simply put, because wait, policy, and policyall are lock-level operations, they are defined in the Object class because the lock belongs to the Object.

18) What is the ThreadLocal variable?

ThreadLocal is a special variable in Java. Each thread has a ThreadLocal, which means that each thread has its own independent variable, and the competition conditions are completely eliminated. It is a good way to get thread security for creating expensive objects. For example, you can use ThreadLocal to make SimpleDateFormat thread-safe, because the class is expensive to create and different instances need to be created for each call, it is not worth using in a local range. If you provide a unique copy of the variable for each thread, this will greatly improve the efficiency. First, reuse reduces the number of expensive objects to be created. Second, you get thread security without using high-cost synchronization or immutability. Another good example of thread local variables is the ThreadLocalRandom class, which reduces the number of Random objects that are expensive to create in a multi-threaded environment.

19) What is FutureTask?

In a Java concurrent program, FutureTask indicates an asynchronous operation that can be canceled. It can start and cancel operations, query whether operations are completed, and retrieve operation results. The result can be retrieved only when the operation is completed. If the operation is not completed, the get method will be blocked. A FutureTask object can encapsulate objects that call Callable and Runnable. Because FutureTask also calls the Runnable interface, it can be submitted to Executor for execution.

20) what are the differences between interrupted and isInterruptedd in Java?

The main difference between interrupted () and isInterrupted () is that the former clears the interrupt status while the latter does not. The interrupt mechanism of Java Multithreading is implemented by using the internal identifier. When Thread. interrupt () is called to interrupt a Thread, the interrupt identifier is set to true. When the interrupt Thread calls the static method Thread. interrupted () to check the interrupt status, the interrupt status is cleared. The non-static method isInterrupted () is used to query the interrupt status of other threads without changing the identifier of the interrupt status. Simply put, any method that throws an InterruptedException exception will clear the interrupt status. In any case, the interruption status of a thread may be changed by the call interruption of other threads.

21) why do the wait and notify methods need to be called in the synchronization block?

This is mainly because Java APIs require this method. If you do not, your code will throw an IllegalMonitorStateException. Another reason is to avoid competing conditions between wait and policy.

22) why should you check the waiting conditions in the loop?

A thread in the waiting state may receive error alarms and false wakeup. If the thread does not check the waiting condition in the loop, the program will exit without meeting the ending condition. Therefore, when a waiting thread wakes up, it cannot be considered that its original waiting status is still valid. It may change during this period after the notify () method is called and before the waiting thread wakes up. This is the reason why the wait () method works better in the loop. You can create a template in Eclipse to call wait and notify for a try. If you want to learn more about this issue, I recommend that you read the thread and synchronization sections in the article "objective Java.

23) What is the difference between a synchronization set and a concurrent set in Java?

Synchronous sets and concurrent sets provide a suitable set of thread security for multithreading and concurrency, but the concurrency set has higher scalability. Before Java, programmers only use the synchronization set and compete for use in multi-thread concurrency, hindering system scalability. Java 5 introduces concurrent sets like ConcurrentHashMap, which not only provides thread security, but also improves scalability by using modern technologies such as lock separation and internal partitioning.

24) What is the difference between heap and stack in Java?

Why is this problem classified into multithreading and concurrent interview questions? Because the stack is a memory area closely related to threads. Each thread has its own stack memory used to store local variables, method parameters, and stack calls. The variables stored in one thread are invisible to other threads. Heap is a public memory area shared by all threads. All objects are created in the heap. To improve the efficiency, the thread will get a cache from the heap to its own stack. If multiple threads use this variable, it may cause problems, in this case, the volatile variable can be used. It requires the thread to read the value of the variable from the main memory.

25) what is a thread pool? Why use it?

It takes a lot of resources and time to create a thread. If a task comes to create a thread, the response time will become longer, and the number of threads that a process can create is limited. To avoid these problems, several threads are created at program startup to respond to them. They are called thread pools, and the threads in them are called worker threads. Since JDK1.5, Java API provides the Executor framework for you to create different thread pools. For example, a single thread pool processes a task each time. A fixed number of thread pools or cache thread pools (a scalable thread pool suitable for programs with many short-lived tasks ).

26) how to write code to solve the producer and consumer problems?

In reality, many of the thread problems you solve belong to the producer consumer model. It is a thread production task for other threads to consume. You must know how to implement inter-thread communication to solve this problem. The lower-level method is to use wait and notify to solve this problem. The better method is to use Semaphore or BlockingQueue to implement the producer and consumer model.

27) how to avoid deadlocks?


Java multi-thread deadlock
A deadlock occurs when two or more processes compete for resources and wait for each other. If no external force is applied, neither of them can proceed. This is a serious problem because the deadlock will cause your program to be suspended and cannot complete the task. The deadlock must meet the following four conditions:

Mutual exclusion condition: a resource can only be used by one process at a time.
Request and retention conditions: when a process is blocked by requesting resources, it will not release the obtained resources.
Non-deprivation condition: resources obtained by a process cannot be forcibly deprived before they are used.
Cyclic waiting condition: a type of cyclic waiting resource relationship is formed between several processes.

The simplest way to avoid deadlock is to stop the loop wait condition and set the flag and sort all the resources in the system, all processes must apply for resources in ascending or descending order to avoid deadlocks.

28) What is the difference between a live lock and a deadlock in Java?

This is the extension of the above question. The Live Lock is similar to the deadlock. The difference is that the status of the thread or process in the active lock is constantly changing. The live lock can be considered as a special hunger. A real example of a live lock is that two people encounter it in a small corridor. Both of them try to avoid the other party so that they can pass through each other. However, because of the same direction, no one can pass through the corridor. Simply put, the main difference between a live lock and a deadlock is that the status of the former process can be changed but cannot be executed.

29) how can I check whether a thread has a lock?

I never knew that we could detect whether a thread has a lock until I attended a telephone interview. In java. lang. Thread, there is a method named holdsLock (), which returns true if and only if the current Thread has a lock for a specific object.

30) how do you get the thread stack in Java?

For different operating systems, there are multiple methods to obtain the Java process thread stack. When you obtain the thread stack, JVM stores the status of all threads to log files or outputs them to the console. In Windows, you can use Ctrl + Break to obtain the thread stack. In Linux, run the kill-3 Command. You can also use the jstack tool to obtain the thread id. You can use the jps tool to find the id.

31) which parameter in JVM is used to control the small stack size of the thread?

This problem is simple. The-Xss parameter is used to control the stack size of a thread.

32) What is the difference between synchronized and ReentrantLock in Java?

Java has been mutually exclusive for a long time only through the synchronized keyword, which has some disadvantages. For example, you cannot extend the methods or block boundary beyond the lock, and cannot cancel them when trying to obtain the lock. Java 5 uses the Lock interface to provide more complex control to solve these problems. The ReentrantLock class implements Lock, which has the same concurrency and memory semantics as synchronized and is also scalable.

33) how can we ensure that three threads T1, T2, and T3 are executed in order?

There are multiple methods in multithreading for the thread to execute in a specific order. You can use the join () method of the thread class to start another thread in one thread, and the other thread completes the thread to continue execution. To ensure the order of the three threads, you should first start the last one (T3 call T2, T2 call T1), so that T1 will be completed first and T3 will be completed finally.

34) What is the role of the yield method in the Thread class?

The Yield method can pause the thread objects currently being executed, so that other threads with the same priority can execute them. It is a static method and only ensures that the current thread does not occupy the CPU, but cannot ensure that other threads will occupy the CPU and execute yield () the thread may be executed immediately after it enters the paused state.

35) What is the concurrency of ConcurrentHashMap in Java?

ConcurrentHashMap divides the actual map into several parts to achieve its scalability and thread security. This division is obtained by the concurrency. It is an optional parameter of the ConcurrentHashMap class constructor. The default value is 16, which avoids contention in the case of multithreading.

36) What is Semaphore in Java?

In Java, Semaphore is a new synchronization class, which is a counting signal. Conceptually, semaphores maintain a license set. If necessary, each acquire () is blocked before the license is available. Add a license for each release (), which may release a blocked recipient. However, if you do not use the actual license object, Semaphore only counts the available license numbers and takes corresponding actions. Semaphores are often used in multi-threaded code, such as database connection pools.

37) if the thread pool queue is full when you submit a task. What will happen at the meeting?

This is a tricky question. Many programmers will think that the task will be blocked until there is space in the thread pool queue. In fact, if a task cannot be scheduled for execution, the ThreadPoolExecutor's submit () method will throw a RejectedExecutionException.

38) What is the difference between the submit () and execute () methods in the Java Thread pool?

Both methods can submit tasks to the thread pool. The return type of the execute () method is void, which is defined in the Executor interface, while the submit () method () the method can return the Future object that holds the computing result. It is defined in the ExecutorService interface and extends the Executor interface. Other thread pool classes such as ThreadPoolExecutor and ScheduledThreadPoolExecutor all have these methods.

39) what is a blocking method?

The blocking method means that the program will wait until the method is completed without doing anything else. The ServerSocket accept () method is always waiting for client connection. Blocking means that the current thread will be suspended until the result is returned. In addition, asynchronous and non-blocking methods are returned before the task is completed.

40) is Swing thread-safe? Why?

You can give a definite answer. Swing is not thread-safe, but you should explain the reason for this answer even if the interviewer did not ask you why. When we say that swing is not thread-safe, we often mention its components. These components cannot be modified in multiple threads. All updates to GUI components must be completed in the AWT thread, swing provides two callback methods, synchronous and asynchronous, for update.

41) What is the difference between invokeAndWait and invokeLater in Java?

The two methods are provided by the Swing API to Java developers to update GUI components from the current thread rather than the event dispatching thread. InvokeAndWait () synchronously updates the GUI component. For example, if a progress bar is updated, the progress bar must be changed accordingly. If the progress is tracked by multiple threads, call the invokeAndWait () method to request the event dispatching thread to update the component accordingly. The invokeLater () method asynchronously calls the update component. For more details, click here.
42) which methods in Swing APIs are thread-safe?

This issue also mentions swing and thread security. Although components are not thread-safe, some methods can be safely called by multiple threads, such as repaint () and revalidate (). The setText () method of JTextComponent and the insert () and append () methods of JTextArea are also thread-safe.

43) how to create an Immutable object in Java?

This problem seems to have nothing to do with multithreading, but immutability helps simplify complicated concurrent programs. Immutable objects can be shared without synchronization, reducing the synchronization overhead for concurrent access to the object. However, Java does not have the annotation @ Immutable. To create an Immutable class, perform the following steps: initialize all members by using the constructor, do not provide the setter method for variables, and declare all members as private. In this way, direct access to these members is not allowed, and in the getter method, do not directly return the object itself, but clone the object and return a copy of the object. My article how to make an object Immutable in Java has a detailed tutorial. After reading this article, you can be confident.

44) What is ReadWriteLock in Java?

Generally, read/write locks are the results of the lock separation technology used to improve the performance of concurrent programs. In Java, ReadWriteLock is an interface added in Java 5. One ReadWriteLock maintains a pair of associated locks, and the other is used for read-only operations and the other is used for writing. When there is no write thread, the next read lock may be held by multiple read threads at the same time. Write locks are exclusive. You can use the ReentrantReadWriteLock in JDK to implement this rule. It supports up to 65535 write locks and 65535 read locks.

45) what is a busy cycle in multithreading?

A busy loop means that programmers use a loop to wait for a thread. Unlike the traditional method of wait (), sleep (), or yield (), they give up CPU control, while a busy loop does not give up CPU, it is running an empty loop. The purpose of this operation is to retain the CPU cache. In a multi-core system, one thread may run in another kernel when it wakes up, which will re-build the cache. It can be used to avoid rebuilding the cache and reduce the waiting time for reconstruction. You can view this article for more information.

46) what are the differences between volatile variables and atomic variables?

This is an interesting question. First, volatile variables and atomic variables look very similar, but have different functions. The Volatile variable ensures the first relation, that is, the write operation will occur before subsequent read operations, but it cannot guarantee atomicity. For example, if you use volatile to modify the count variable, the count ++ operation is not atomic. The atomic method provided by the AtomicInteger class can make this operation atomic. For example, the getAndIncrement () method will perform atomic incremental operations to increase the current value by one, similar operations can be performed on other data types and referenced variables.

47) what will happen if the thread in the synchronization block throws an exception?

This question has pitted many Java Programmers. If you can think of whether to release the lock to answer this question, you still want to answer it correctly. No matter whether your synchronization block is normal or unexpectedly exited, the threads in it will release the lock, so I prefer the synchronization block compared to the lock interface, because it does not require me to spend time releasing the lock, this function can be implemented by releasing locks in the finally block.

48) What is the dual-check lock in Singleton mode?

This question is frequently asked during Java interviews, but the interviewer is only 50% satisfied with answering this question. Half of us cannot write double-check locks, and half of us cannot tell about its hidden dangers and how Java1.5 corrected it. It is actually an old method used to create a thread-safe Singleton. When a singleton instance is created for the first time, it tries to use a single lock for performance optimization, however, because it is too complicated, JDK1.4 fails, and I personally do not like it. In any case, even if you do not like it, you still need to understand it because it is often asked.

49) how to create a thread-safe Singleton in Java?

This is the follow-up of the above question. If you do not like the double check lock and the interviewer asks an alternative method to create the Singleton class, you can use the JVM class loading and static variable initialization features to create a Singleton instance, or use the enumeration type to create a Singleton instance. I like this method very much.

50) write 3 best practices for multithreading that you follow

I like this problem most. I believe you will follow some best practices when writing concurrent code to improve performance. I think most Java programmers should follow the following three best practices:

Give your thread a meaningful name.
This allows you to easily find bugs or track them. OrderProcessor, QuoteProcessor or TradeProcessor is better than Thread-1. thread-2 and Thread-3 are much better. Give the Thread a name related to the task to be completed. All major frameworks and even JDK follow this best practice.
Avoid locking or narrowing the synchronization scope
The lock cost is high and context switching is more time-consuming. Try to minimize the use of synchronization and lock to narrow down the critical section. Therefore, I prefer the synchronization block as opposed to the synchronization method. It gives me absolute control over the lock.
Multi-purpose synchronization class: less wait and policy
First, the CountDownLatch, Semaphore, CyclicBarrier, and Exchanger synchronization classes simplify the coding operations, and it is difficult to control the complex control flow with wait and policy. Second, these classes are written and maintained by the best companies. They will be constantly optimized and improved in the future JDK. Using these higher-level synchronization tools, your program can be optimized without any effort.
Multi-purpose concurrent set and less synchronization set
This is another best practice that is easy to follow and has benefited a lot. Concurrent sets have better scalability than synchronous sets, so concurrent sets are better used in concurrent programming. If you need map next time, you should first think of ConcurrentHashMap.

51) how to force a thread to be started?

This problem is like how to force Java garbage collection. At present, there is no way, although you can use System. gc () for garbage collection, but it is not guaranteed to succeed. In Java, there is no way to force a thread to be started. It is controlled by the thread scheduler and Java has not published relevant APIs.

52) What is the fork join framework in Java?

The fork join framework is an efficient tool in JDK 7. Java developers can use it to take full advantage of the multi-processor on modern servers. It is designed specifically for those that can be divided into many sub-modules recursively, with the aim of using all available processing capabilities to improve program performance. A major advantage of the fork join framework is that it uses a work stealing algorithm to complete more multi-task work threads and steal tasks from other threads for execution. You can view this article for more information.

53) What is the difference between calling the wait () and sleep () methods in Java Multithreading?

In Java programs, wait and sleep will cause some form of pause, which can meet different needs. The wait () method is used for inter-thread communication. If the waiting condition is true and other threads are awakened, it will release the lock while sleep () the method only releases CPU resources or stops the current thread for a period of time, but does not release the lock.

66) now there are three threads T1, T2, and T3. How do you ensure that T2 is executed after T1 execution and T3 is executed after T2 execution?

This thread is usually asked during the first round or telephone interview to check if you are familiar with the join method. This multithreading problem is relatively simple and can be implemented using the join method.

67) in Java, what are the advantages of the Lock interface over the synchronized block? You need to implement an efficient cache, which allows multiple users to read but only allows one user to write to maintain its integrity. How do you implement it?

The biggest advantage of the lock interface in multi-thread and concurrent programming is that they provide locks for read and write respectively, which can meet your needs to write high-performance data structures such as ConcurrentHashMap and implement conditional blocking. Questions about Java thread interviews are increasingly answered by the interviewer. I strongly recommend that you carefully read Locks before attending a multi-thread interview, because it is currently used to build a large number of client caches and transaction connection spaces for the final electronic transaction system.

68) what are the differences between the wait and sleep methods in java?

Java thread interview questions that are frequently asked during telephone interviews. The biggest difference is that wait releases the lock while waiting, and sleep keeps holding the lock. Wait is usually used for interaction between threads, and sleep is usually used to suspend execution.

69) use Java to implement blocking queues.

This is a relatively difficult multi-thread interview problem, which can achieve many goals. First, it can check whether the selector can actually write a program using a Java thread; second, it can check the selector's understanding of the concurrent scenario, and you can ask a lot of questions based on this question. If you use the wait () and notify () methods to implement blocking queues, you can ask him to write it again using the concurrent class in the latest Java 5.

60) use Java to write code to solve the producer-consumer problem.

This is similar to the above question, but it is more classic. In some cases, the following questions will be asked during the interview. In Java, there are many solutions to the producer-consumer problem. I have already shared a method to implement blocking queues. In some cases, they may even ask how to achieve the dining of philosophers.

61) how do you solve the deadlock caused by programming in Java?

This is my favorite Java thread interview question, because even if the deadlock problem is very common when writing multi-threaded concurrent programs, many candidates cannot write the deadlock free code (no deadlock code ?), They are struggling. Just tell them that you have N resources and N threads, and you need all resources to complete an operation. In order to make it simple, here n can be replaced with 2, the larger the data will make the problem look more complicated. You can get more information about deadlocks by avoiding deadlocks in Java.

62) what are atomic operations and what are atomic operations in Java?

This is a very simple java thread interview question. The next question is that you need to synchronize an atomic operation.

63) What is the key role of volatile in Java? How to use it? In Java, what is the difference between it and the synchronized method?

Since the Java 5 and Java memory models have changed, thread issues based on the volatile keyword have become increasingly popular. You should be prepared to answer questions about how volatile variables ensure visibility, order, and consistency in the concurrency environment.

64) what are the competitive conditions? How do you find and solve the competition?

This is a problem that occurs in the advanced stage of multi-thread interviews. Most interviewers will ask about your recent competitive conditions and how you solve them. Some time they will write simple code and then let you detect the competition conditions of the code. Refer to my previous article on Java competition conditions. In my opinion, this is one of the best java thread interview questions. It can precisely detect the candidate's experience in solving the competition conditions, or writing code which is free of data race or any other race condition. The best book in this regard is Concurrency practices in Java.

65) how will you use thread dump? How will you analyze Thread dump?

In UNIX, you can use kill-3, and thread dump will print logs. In windows, you can use CTRL + Break ". Very simple and professional thread interview questions, but if he asks you how to analyze it, it will be tricky.

66) Why can't we directly call the run () method when we call the start () method?

This is another classic java multi-thread interview question. This is also the confusion when I first started writing a thread program. This question is usually asked by phone or in the first round of the preliminary and intermediate Java interview. The answer to this question should be like this. When you call the start () method, you will create a new thread and execute the code in the run () method. However, if you call the run () method directly, it does not create a new thread or execute the code that calls the thread. Read the article "differences between the start and run methods" I wrote to get more information.

67) how do you wake up a blocked thread in Java?

This is a tricky question about threads and blocking, and it has many solutions. If the thread encounters IO blocking, I don't think there is a way to abort the thread. If the thread is blocked by calling the wait (), sleep (), or join () method, you can interrupt the thread and throw InterruptedException to wake it up. I wrote a lot about How to deal with blocking methods in java.

68) What is the difference between CycliBarriar and CountdownLatch in Java?

This thread problem is mainly used to check whether you are familiar with and send packets in JDK 5. The difference between the two is that javasicbarrier can reuse the obstacles that have been passed, while CountdownLatch cannot be reused.

69) what is an immutable object and how does it help write concurrent applications?

Another typical multi-thread interview question is not directly related to threads, but it is helpful indirectly. This java interview question can be very tricky. If he asks you to write an immutable object or ask you why the String is immutable.

70) what are the common problems you encounter in a multi-threaded environment? How did you solve it?

Memory-interface, competitive conditions, deadlocks, live locks, and hunger are often encountered in multithreading and concurrent programs. There is no end to the problem. If you make a mistake, it will be difficult to find and debug it. This is mostly based on interviews, rather than Java thread issues based on actual applications.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.