50-way Java thread face Test (classic) _java

Source: Internet
Author: User
Tags connection pooling finally block garbage collection semaphore sleep thread class volatile cpu usage

Here are some popular Java thread-related interview questions that you can use to prepare for the interview.

1 What is a thread?

A thread is the smallest unit of operation that the operating system can perform, which is included in the process and is the actual unit of operation in the process. Programmers can do multiprocessor programming through it, and you can use multithreading to speed up compute-intensive tasks. For example, if a thread completes a task for 100 milliseconds, it takes only 10 milliseconds to complete the task with 10 threads. Java provides excellent support for multithreading at the language level, and it is also a good selling point. For more details please click here.

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

A thread is a subset of a process, a process can have many threads, and each thread performs a different task in parallel. Different processes use different memory space, and all threads share the same memory space. Do not confuse it with stack memory, each thread has a separate stack of memory to store local data. Please click here for more details.

3 How do I implement threads in Java?

There are two ways to do it at the level of language. An instance of the Java.lang.Thread class is a thread but it needs to invoke the Java.lang.Runnable interface to execute, because the thread class itself is the calling Runnable interface so you can inherit the Java.lang.Thread class or directly invoke the Runnable interface to override the run () method to implement the thread. Please click here for more details.

4 with Runnable or Thread?

This question is a follow-up to the previous question, and we all know that we can implement threads by inheriting the thread class or by invoking the Runnable interface, and the question is, is that the better method? Under what circumstances is it used? This question is easy to answer if you know that Java does not support multiple inheritance of classes, but allows you to invoke multiple interfaces. So if you're going to inherit other classes, it's certainly a good call to the Runnable interface. Please click here for more details.

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

This question is often asked, but it is still possible to differentiate the participants ' understanding of the Java threading model. The start () method is used to start a newly created thread, and the Run () method is called internally in Start (), which is not the same as the effect of calling the run () method directly. When you call the run () method, it is only invoked in the original thread, and no new thread starts, and the start () method starts the new thread. More discussion please click here

7 What is the difference between Runnable and callable in Java?

Both Runnable and callable represent the tasks that are to be performed on different threads. Runnable started from JDK1.0, callable was added in JDK1.5. The main difference is that the callable call () method can return a value and throw an exception, while the Runnable run () method does not have these features. Callable can return a Future object loaded with a calculated result. My blog has a more detailed description.

8 What is the difference between Cyclicbarrier and Countdownlatch in Java?

Both Cyclicbarrier and Countdownlatch can be used to allow a set of threads to wait for other threads. Unlike Cyclicbarrier, Countdownlatch cannot be reused. Click here to see more information and sample code.

9 What is the Java memory model?

The Java memory model prescribes and directs Java programs to behave in a deterministic manner between different memory architectures, CPUs, and operating systems. It is especially important in the case of multithreading. The Java memory model provides assurance that changes made to one thread can be seen by other threads, and that they are first-sex. This relationship defines a number of rules that allow programmers to have a clearer idea of concurrent programming. For example, having sex in advance ensures that:

Code within a thread can be executed sequentially, which is called the program order rule.

For the same lock, a unlock operation must occur before another locking operation that occurs after the time, also known as the pipe lock rule.

The previous write operation on volatile is also called the volatile variable rule before the read operation of the latter volatile.

Any operation within a thread must be called the thread initiation rule after the start () Call of this thread.

The thread terminates the rule before all operations of a thread terminate.

An object's finalization operation must be called an object finalization rule after the object is constructed.

of transitivity

I strongly recommend that you read the 16th chapter of Java Concurrent programming practice to deepen your understanding of the Java memory model.

What is the volatile variable in Java?

Volatile is a special modifier that only member variables can use. In cases where a Java concurrency program lacks a synchronization class, the operation of a multithreaded member variable is transparent to other threads. The volatile variable guarantees that the next read operation will occur after the previous write operation, which is the volatile variable rule for the previous question. Click here to see more volatile.

11 What is thread-safe? is Vector a thread-safe class? (see here for details)

If you have more than one thread running at the same time in the process where your code is located, these threads may run the code at the same time. If the result of each run is the same as that of a single-threaded operation, and the value of other variables is the same as expected, it is thread-safe. The same instance object of a thread-safe counter class will not have a miscalculation if it is used by multiple threads. Obviously you can divide the collection class into two groups, thread-safe and not-thread-safe. Vector is a synchronous method for thread-safe, and ArrayList similar to it is not thread-safe.

What is a race condition in Java? Give an example to illustrate.

A race condition can cause a program to appear bugs in concurrent situations. Multithreading to some resources when the competition will produce a race condition, if the first to execute the process of competition failure to follow the execution, then the entire program will appear some uncertain bugs. This bugs is hard to find and repeats itself because of random competition between threads. An example is an unordered process, as detailed in the answer.

How do I stop a thread in Java?

Java provides a rich API but does not provide an API for stopping threads. JDK 1.0 had some control methods like Stop (), suspend (), and resume () but because of the potential deadlock threat they were discarded in subsequent JDK versions, then the Java API designers did not provide a compatible and thread-safe way to stop a line Ride. When the run () or call () method finishes, the thread ends automatically, and if you want to manually end a thread, you can use the volatile Boolean variable to exit the loop of the run () method or cancel the task to break the thread. Click here to view the sample code.

14 What happens when an exception occurs while a thread is running?

This is a very tricky Java interview question I met in an interview, and simply said that the thread would stop executing if the exception was not captured.

Thread.uncaughtexceptionhandler is an inline interface used to handle a sudden interruption of a thread caused by an unhandled exception. When an unhandled exception causes a thread to break, the JVM uses Thread.getuncaughtexceptionhandler () to query the thread's Uncaughtexceptionhandler and pass the thread and exception as arguments to the The handler Uncaughtexception () method is processed.

15 How to share data between two threads?

You can do this by sharing objects, or by using data structures such as concurrency, such as blocking queues. This tutorial, "Java Thread Communication" (which involves sharing objects among two threads) implements the producer consumer model using the wait and Notify methods.

What is the difference between notify and Notifyall in Java?

This is another tricky question, because multithreading can wait for a single monitor lock, and Java API designers provide methods to notify them when waiting for conditions to change, but these methods are not fully implemented. The Notify () method does not wake a specific thread, so only one thread is available when it waits. Notifyall () wakes up all threads and allows them to scramble for locks to ensure that at least one thread continues to run. My blog has more detailed information and sample code.

17 Why wait, notify and notifyall These methods are not in the thread class?

This is a design-related issue that examines the interviewer's view of the existing system and some common but seemingly unreasonable things. To answer these questions, you need to explain why it makes sense to put these methods in the Object class and why you don't put them in the Thread class. One obvious reason is that the locks provided by JAVA are object-level rather than thread-level, and each object has a lock, which is obtained by thread. It is meaningful to call the wait () method in an object if the thread waits for some locks. If the wait () method is defined in the thread class, it is not obvious which lock the thread is waiting for. Simply put, since wait,notify and Notifyall are both lock-level operations, they are defined in the object class because the lock belongs to the object. You can also view this article to learn more.

18 What is the ThreadLocal variable?

ThreadLocal is a special variable in Java. Each thread has a ThreadLocal that each thread has its own independent variable, and the competitive conditions are completely eliminated. It's a good way to get thread-safe for creating expensive objects, such as you can use ThreadLocal to turn SimpleDateFormat into thread-safe, because that class creation is expensive and each call needs to create a different instance so it's not worth using it locally, If you provide each thread with a copy of its own unique variable, you will greatly increase your efficiency. First, it reduces the number of expensive objects created by multiplexing. Second, you get thread safety without using high cost synchronization or invariance. Another good example of a thread-local variable is the Threadlocalrandom class, which reduces the number of Random objects that are expensive to create in a multithreaded environment. See answers for more information.

19 What is Futuretask?

In a Java concurrency program, Futuretask represents an asynchronous operation that can be canceled. It has the methods of starting and canceling operations, whether the query operation is completed and the result of retrieving the operation. The result can be retrieved only when the operation is complete, and the Get method will block if the operation has not yet been completed. A Futuretask object can be wrapped over an object that invokes callable and Runnable, and because Futuretask also invokes the Runnable interface, it can be submitted to Executor for execution.

The difference between interrupted and Isinterruptedd methods in Java?

The main difference between interrupted () and isinterrupted () is that the former will remove the interrupt state and the latter will not. The Java multithreading interrupt mechanism is implemented with an internal identity, and calling Thread.Interrupt () to interrupt a thread sets the interrupt identity to true. When a thread calls a static method thread.interrupted () to check the interrupt state, the interrupt state is zeroed. Instead of the static method isinterrupted () is used to query the interrupt state of other threads and does not change the interrupt status identity. Simply put, any method that throws a Interruptedexception exception will zero the interrupt state. In any case, the interrupt state of one thread may be changed by a call to interrupt by another thread.

21 Why wait and notify methods are called in the sync block?

The main reason is that the Java API enforces this, and if you don't, your code throws a Illegalmonitorstateexception exception. Another reason is to avoid the competing conditions between wait and notify.

22 Why should you check the waiting condition in the loop?

A thread in the waiting state may receive error alerts and pseudo wakes, and if the wait condition is not checked in the loop, the program exits without satisfying the end condition. Therefore, when a waiting thread wakes up, it is not possible to assume that its original wait state is still valid, and that it may change after the Notify () method call and before the waiting thread wakes up. This is why using the Wait () method in a loop works better, and you can create templates in Eclipse to call wait and notify to try. If you want to learn more about this issue, I recommend that you read the threads and sync chapters in the effective Java book.

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

Both synchronous and concurrent collections provide an appropriate set of thread-safe collections for multithreading and concurrency, although the concurrency collection is more extensible. Prior to Java1.5, programmers had only synchronized sets to use and would cause contention when multithreaded concurrency hindered the scalability of the system. JAVA5 introduces concurrent sets like Concurrenthashmap, which not only provide thread safety but also improve scalability with modern techniques such as lock separation and internal partitioning. See the answer for more details.

What is the difference between stacks and stacks in Java?

Why is this problem categorized in multithreaded and concurrent face questions? Because the stack is an area of memory that is tightly related to threads. Each thread has its own stack memory for storing local variables, method parameters, and stack calls, and variables stored in one thread are not visible to other threads. The heap is a common memory area shared by all threads. Objects are created in the heap, in order to enhance the efficiency of the thread will be a cache from the heap to their own stack, if multiple threads use the variable may cause problems, then the volatile variable can play a role, it requires the thread from main memory read the value of the variable.

See the answer for more details.

25 What is a thread pool? Why do you use it?

Creating a thread takes expensive resources and time, and if the task comes to create a thread, the response time becomes longer and the number of threads a process can create is limited. To avoid these problems, create a number of thread response processing at the start of the program, called the thread pool, where the threads are called worker threads. Starting with JDK1.5, the Java API provides a Executor framework that allows you to create different thread pools. such as a single thread pool, one task at a time, a fixed number of thread pools or a cache thread pool (an extensible thread pool for programs that fit many short-lived tasks). See this article for more details.

26 How to write code to solve the problem of producer consumers?

Many of the threading problems you solve in the real world belong to the producer consumer model, which is a thread production task for other threads to consume, and you must know how to communicate between threads to solve the problem. The lower-level approach is to use wait and notify to solve this problem, the better way is to use semaphore or blockingqueue to achieve the producer consumer model, this tutorial has to achieve it.

27 How to avoid deadlock?

Deadlock in Java Multi-threading

Deadlock refers to two or more than two processes in the implementation process, as a result of contention for resources caused by a mutual wait for the phenomenon, without external forces, they will not be able to push down. This is a serious problem, because deadlocks will cause your program to suspend the task, the deadlock must meet the following four conditions:

Mutex: A resource can be used by only one process at a time.

Request and retention conditions: a process that is blocked by requesting resources, retains the resources that have been acquired.

Non-deprivation of conditions: the resources that the process has acquired cannot be forcibly deprived until the end of use.

Loop wait Condition: A circular wait resource relationship is formed between several processes.

The easiest way to avoid deadlocks is to block the loop waiting condition, set all the resources in the system to a flag bit, sort, and specify that all process request resources must operate in a certain order (ascending or descending) to avoid deadlocks. This tutorial has the details of the code example and the discussion to avoid deadlocks.

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

This is the extension of the title, live lock and deadlock similar, the difference is that the status of the thread or process in the active lock is constantly changing, the living lock can be considered a special hunger. An example of a real live lock is two people in a narrow corridor, two people try to avoid each other to pass, but because the direction of avoidance is the same as the end of no one through the corridor. Simply put, the main difference between a live lock and a deadlock is that the state of the former process can be changed but cannot continue.

29 How to detect whether a thread has a lock?

I never knew we could detect if a thread had a lock until I took a phone interview. In Java.lang.Thread, there is a method called Holdslock (), which returns true if and only if the thread has a lock on a specific object. You can check out this article for more.

30 How do you get the thread stack in Java?

For different operating systems, there are several ways to get a thread stack of Java processes. When you get the thread stack, the JVM saves the state of all threads to the log file or to the console. In Windows you can use CTRL + BREAK combination keys to get the thread stack, Linux with the kill-3 command. You can also use the Jstack tool to get, it operates on the thread ID, you can use the JPS tool to find the ID.

Which parameter in the JVM is used to control the thread's stack stack small

The problem is simple, and the-XSS parameter is used to control the stack size of the thread. You can look at the JVM configuration list to learn more about this parameter.

What is the difference between synchronized and Reentrantlock in Java?

Java in the past a long time only through the Synchronized keyword to achieve mutual exclusion, it has some drawbacks. For example, you can not extend the lock outside the method or block boundaries, try to acquire the lock can not be canceled halfway. Java 5 solves these problems by providing more complex controls through the Lock interface. The Reentrantlock class implements Lock, which has the same concurrency and memory semantics as the synchronized, and it is extensible. You can check out this article for more

33 has three threads t1,t2,t3, how do you make sure that they are executed sequentially?

There are several ways to have threads execute in a specific order in multiple threads, and you can use the join () method of the thread class to start another thread in one thread and another thread to complete the thread to execute. To ensure the order of three threads you should first start the last one (T3 call t2,t2 call T1), so that T1 will complete first and T3 finally complete. You can check out this article for more.

What is the effect of the yield method in the Thread class?

The Yield method can suspend the currently executing thread object, allowing other threads with the same priority to execute. It is a static method and only guarantees that the current thread discards CPU usage and does not guarantee that other threads must be able to occupy the CPU, and that the thread executing yield () may be executed immediately after it has entered the paused state. Click here to find out more about the yield method.

What is the concurrency degree of concurrenthashmap in Java?

Concurrenthashmap the actual map into several parts to achieve its scalability and thread safety. This division is obtained using concurrency, which is an optional parameter to the Concurrenthashmap class constructor, with a default value of 16, which avoids contention in multi-threaded situations. To learn more about concurrency and internal sizing Please read my article How to Concurrenthashmap works in Java.

What is semaphore in Java?

The semaphore in Java is a new synchronization class, which is a counting signal. Conceptually, the semaphore maintains a set of permissions. If necessary, each acquire () is blocked before the license is available, and then the license is obtained. Each release () adds a license that may free a blocking user. However, without using the actual license object, semaphore only counts the number of available licenses and takes action accordingly. Semaphores are often used in multithreaded code, such as database connection pooling. Please click here for more details.

37 If you submit a task, the thread pool queue is full. What will happen when the hair is born?

This is a tricky question, and many programmers will assume that the task will block until there is an empty thread pool queue. In fact, if a task cannot be scheduled to execute then Threadpoolexecutor ' s Submit () method throws a Rejectedexecutionexception exception.

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

Two methods can submit tasks to the thread pool, the return type of the Execute () method is void, it is defined in the Executor interface, and the Submit () method can return the Future object that holds the result of the calculation, which is defined in the Executorservice interface, which expands The Executor interface is presented, and other thread pool classes like Threadpoolexecutor and Scheduledthreadpoolexecutor have these methods. Please click here for more details.

39 What is a blocking method?

The blocking method is that the program waits until the method completes without doing anything else, and the ServerSocket accept () method is waiting for the client to connect. Blocking here means that the current thread will be suspended until the result of the call is returned. In addition, there are asynchronous and Non-blocking methods that are returned before the task is completed. Please click here for more details.

is Swing a thread-safe? Why?

You can say with certainty that Swing is not thread-safe, but you should explain why this is the answer, even if the interviewer doesn't ask you why. When we say that swing is not thread-safe and often mentions its components, these components cannot be modified in multiple threads, all updates to the GUI components are done in the AWT thread, and swing provides both synchronous and asynchronous callback methods for updating. Click here to see more about swing and thread safety.

What is the difference between invokeandwait and Invokelater in Java?

These two methods are provided by the Swing API to Java developers to update the GUI components from the current thread instead of the event distribution thread. Invokeandwait () synchronously updates the GUI components, such as a progress bar, and once the progress is updated, the progress bar changes accordingly. If progress is tracked by multiple threads, call the Invokeandwait () method to request the event-issuing thread to update the component accordingly. The Invokelater () method invokes the update component asynchronously. Please click here for more details.

What are the methods in the Swing API that are thread safe?

This issue also mentions swing and thread safety, although components are not thread-safe, but there are some methods that can be invoked by multi-threaded security, such as repaint (), revalidate (). The JTextComponent SetText () method and the JTextArea insert () and append () methods are also thread-safe.

43 How do I create a immutable object in Java?

This problem does not seem to have anything to do with multithreading, but invariance helps to simplify already complex concurrent programs. The immutable object can be shared without synchronization, reducing the synchronization overhead of concurrent access to the object. However, Java does not @immutable this specifier, to create immutable classes, to implement the following steps: To initialize all members by constructing methods, not to provide setter methods for variables, to declare all members private, so that you do not allow direct access to these members, in the Getter method , instead of directly returning the object itself, clones the object and returns a copy of the object. I have a detailed tutorial in my article how to make a object immutable in Java, and you can be confident when you read it.

What is the Readwritelock in Java?

In general, read-write locks are the result of locking separation techniques used to enhance the performance of concurrent programs. The Readwritelock in Java is a new interface in Java 5, a readwritelock maintains a pair of associated locks, one for read-only operations and one for writing. A read lock may be held by multiple read threads at the same time without a write thread. Write locks are exclusive, and you can use the Reentrantreadwritelock in JDK to implement this rule, which supports up to 65,535 write locks and 65,535 read locks.

45 What is a busy loop in multiple threads?

Busy loops are programmers who use loops to keep a thread waiting, unlike the traditional method wait (), sleep () or yield () they all give up CPU control, and the busy loop does not give up the CPU, it is running an empty loop. The purpose of this is to preserve the CPU cache, in which a waiting thread wakes up in another kernel and then rebuilds the cache. You can use it to avoid rebuilding the cache and to reduce the time it is waiting to rebuild. You can view this article for more information.

What is the difference between the volatile variable and the atomic variable?

This is an interesting question. First, the volatile variable and the atomic variable look alike, but the functionality is different. The Volatile variable ensures that the antecedent is a write operation that occurs before the subsequent read operation, but it does not guarantee atomicity. For example, using volatile to modify the count variable, the count++ operation is not atomic. The atomic method provided by the Atomicinteger class allows the operation to have atomicity such as the Getandincrement () method to incrementally increment the current value by one, and other data types and reference variables can perform similar operations.

47 What happens if a thread in the synchronization block throws an exception?

This problem pits a lot of Java programmers, if you can think of whether the lock release this clue to answer a little hope to correct. Whether your sync block is normal or abnormal exit, the inside of the thread will release the lock, so the contrast lock interface I prefer to sync block, because it does not have to spend my energy to release the lock, the function can be in the finally block release lock implementation.

48 single case mode of double check lock is what?

This question is often asked in a Java interview, but the interviewer is only 50% satisfied with answering the question. Half the people can't write a double check lock and half of them can't say how it's hidden and how it's Java1.5. It's actually an old way to create a single example of thread safety, and when a singleton instance is first created it tries to optimize for performance with a single lock, but because it's too complicated, it's a failure in JDK1.4 and I personally don't like it. In any case, even if you don't like it, you need to know it, because it's often asked. You can find out more about how to double checked locking on the Singleton works article.

49 How to create thread-safe Singleton in Java?

This is the follow-up to the above question, if you don't like the double check lock and the interviewer asks for an alternative to creating the Singleton class, you can use the JVM's class load and static variable initialization features to create a Singleton instance, or use an enumeration type to create a Singleton. I like to use this method very much. You can view this article for more information.

50 write out 3 multithreaded best practices that you follow

This is a problem I like best, and I'm sure you'll follow some of the best practices when writing concurrent code to improve performance. Here are three best practices I think most Java programmers should follow:

Give your thread a meaningful name.

This makes it easy to find bugs or track. Orderprocessor, quoteprocessor or tradeprocessor this name than Thread-1. Thread-2 and Thread-3 are much better, giving the thread a name associated with the task it is about to complete, and all the major frameworks and even the JDK follow this best practice.

Avoid locking and narrowing the scope of synchronization

Locking costs are expensive and context switching is more time-consuming, try to minimize the use of synchronization and locks, narrowing the critical area. So I prefer the sync block to the Sync method, which gives me absolute control over the lock.

Multi-use synchronization classes with less wait and notify

First, Countdownlatch, Semaphore, Cyclicbarrier, and exchanger These synchronization classes simplify coding operations, and it is difficult to control complex control flows with wait and notify. Second, these classes are written and maintained by the best enterprises in subsequent JDK and they are continually optimized and refined, and your programs can be optimized using these higher-level synchronization tools.

Multi-use concurrent sets less synchronization set this is another easy to follow and benefit a great best practice, the concurrency collection is better than the extensibility of the synchronization set, so it is better to use concurrent sets in concurrent programming. If you need to use map next time, you should first think about using Concurrenthashmap. My article has a more detailed description of the Java concurrency collection.

51 How do I force a thread to start?

This problem is like how to force Java garbage collection, and there is no way to think of it, although you can use System.GC () for garbage collection, but not guaranteed to succeed. In Java there is no way to force a thread to start, it is controlled by the thread scheduler and Java does not advertise the relevant APIs.

What is the fork join framework in Java?

The fork join framework is an efficient tool in JDK7 that allows Java developers to take advantage of multiprocessor on modern servers. It is designed specifically for those that can be recursively partitioned into many sub modules, with the aim of using all available processing capabilities to promote program performance. A huge advantage of the fork join framework is that it uses a work-stealing algorithm that can be done by stealing tasks from other threads. You can view this article for more information.

What is the difference between invoking the wait () and the Sleep () method in a Java multi-thread?

Both wait and sleep in a Java program cause some form of pause that can meet different needs. The wait () method is used for communication between threads, and if the waiting condition is true and other threads are awakened, it releases the lock, while the sleep () method frees up only CPU resources or allows the current thread to stop execution for a period of time but does not release the lock. You can view this article for more information.

Related Article

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.