Java Thread Surface Questions

Source: Internet
Author: User

In a typical Java interview, the interviewer asks the basic concepts of the thread, such as: why you need to use threads, how to create threads, and how to create threads better (for example, inheriting the thread class or calling the Runnable interface), And then gradually asked what concurrency problems were like in Java concurrency programming, Java memory model, JDK1.5 introduced higher-order concurrency tools, concurrent programming common design patterns, classic multithreading problems such as producer consumers, philosophers dining, readers or simple bounded buffer problems. Just knowing the basic concept of threading is far from enough, you must know how to deal with the concurrency problems such as deadlock, race condition, memory conflict and line Cheng. With these tips, you can easily handle multithreading and concurrent interviews.

It's normal for many Java programmers to go to the interview before the interview. Because collecting face questions and exercises took time, I collected 50 hot questions from many interviewers about Java multithreading and concurrency. I only collected more new face questions and did not provide all the answers. Presumably smart you are aware of these issues, and if you do not understand the problem, you can use Google to find the answer.

1 What is a thread?

A thread is the smallest unit that the operating system can perform operations on, which is included in the process and is the actual operating unit of the process. Programmers can use it for multiprocessor programming, and you can speed up operations-intensive tasks using multithreading. For example, if a thread takes 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 level, and it is also a good selling point.

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

A thread is a subset of processes, a process can have many threads, and each thread performs different tasks in parallel. Different processes use different memory spaces, and all threads share the same amount of memory space. Don't confuse it with stack memory, each thread has a separate stack of memory to store local data.

3 How do I implement threads in Java?

There are two ways to speak at the language level. An instance of the Java.lang.Thread class is a thread but it needs to invoke the Java.lang.Runnable interface to execute, since the thread class itself is the runnable interface of the call so you can inherit Java.lang.Thread Class or call the Runnable interface directly to override the run () method to implement the thread.

4 with runnable or thread?

The question is the follow-up, and we all know that we can implement threads by inheriting the thread class or calling the Runnable interface, and the question is, what better way? Under what circumstances should it be 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, of course it's OK to call the Runnable interface.

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

This question is often asked, but it is still possible to differentiate from the way in which the participants understand the Java threading model. The start () method is used to start the newly created thread, and start () calls the run () method internally, which is not the same as calling the run () method directly. When you call the run () method, only the original thread is called, no new thread is started, and the start () method starts the new thread.

What is the difference between runnable and callable in 6Java?

Both runnable and callable represent tasks that you want to perform in different threads. Runnable from the JDK1.0 began, callable is in the JDK1.5 increase. 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. The callable can return a future object loaded with calculated results.

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

Both Cyclicbarrier and Countdownlatch can be used to allow a group of threads to wait for other threads. Unlike Cyclicbarrier, Countdownlatch cannot be reused.

What is the 8Java 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 guarantees that changes made by one thread can be visible to other threads, and that they are first-rate. This relationship defines rules that allow programmers to have a clearer idea of concurrent programming. For example, prior sex ensures that:
The code within the thread can be executed in a sequential order, which is called the program order rule.
For the same lock, an unlock operation must occur after another lock operation that occurs after the time, also known as a pipe lock rule.
The previous write to volatile is also called a volatile variable rule before the next volatile read operation.
Any operation within a thread must be called after the start () Call of this thread, also known as the thread initiation rule.
A thread terminates the rule before all operations on a thread are terminated.
The end operation of an object must also be called an object finalization rule after the object is constructed.
Transitivity
I strongly recommend that you read the 16th chapter of Java Concurrency Programming practice to deepen your understanding of the Java memory model.

What are the volatile variables in 9Java?

Volatile is a special modifier that can only be used by member variables. Multithreaded operations on member variables are transparent to other threads in the absence of a synchronization class for Java concurrency programs. The volatile variable guarantees that the next read will occur after the previous write operation, which is the volatile variable rule for the previous question.

10 What is thread safety? is vector a thread-safe class?

If your code is in a process where multiple threads are running at the same time, these threads may run the code at the same time. If the result of each run is the same as the single-threaded run, and the value of the other variable is the same as expected, it is thread-safe. The same instance object of a thread-safe counter class will not have a computational error if it is used by multiple threads. Obviously you can divide the collection classes into two groups, thread-safe and non-thread-safe. Vectors are thread-safe with synchronous methods, and ArrayList similar to it are not thread-safe.

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

A race condition causes the program to have some bugs in the concurrency situation. Multi-threaded to some of the resources of the competition when the situation will produce a race condition, if the first to execute the program competition failure platoon to execute, then the entire program will appear some uncertain bugs. This bugs is difficult to find and will recur because of random competition between threads.

How do I stop a thread in 12Java?

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

What happens when 131 threads run with an exception?

This is a very tricky Java interview that I met in an interview, which simply says that the thread will stop executing if the exception is not captured. Thread.uncaughtexceptionhandler is an inline interface for dealing with abrupt interruptions of threads caused by uncaught exceptions. When an uncaught exception causes the thread to break, the JVM uses Thread.getuncaughtexceptionhandler () To query the thread's Uncaughtexceptionhandler and pass the thread and exception as arguments to the handler's Uncaughtexception () method for processing.

14 How do I share data between two threads?

You can do this by sharing objects, or by using a data structure that is concurrent like a blocking queue. This tutorial, "Java Inter-thread communication," which involves sharing objects between two threads, implements the producer consumer model with the wait and notify methods.

What is the difference between notify and Notifyall in 15Java?

This is another tricky question, because multithreading can wait for single-monitor locks, and Java API designers provide methods to notify them when they wait for conditions to change, but these methods are not fully implemented. The Notify () method does not wake up a specific thread, so only one thread waits for it to be useful. Notifyall () Wakes all threads and allows them to scramble for locks to ensure that at least one thread can continue to run.

16 Why wait, notify and notifyall These methods are not inside the thread class?

This is a design-related issue that examines the interviewer's view of the existing system and some common but seemingly irrational things. To answer 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 locks provided by Java are object-level rather than thread-level, and each object has a lock, which is obtained through the thread. The wait () method in the calling object is meaningful 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, because Wait,notify and Notifyall are both lock-level operations, they are defined in the object class because the locks belong to the objects. You can also check this article to learn more.

17 What is a threadlocal variable?

Threadlocal is a special variable in Java. Each thread has a threadlocal that each thread has its own independent variable, and the race condition is completely eliminated. It is a good way to get thread-safe for creating expensive objects, such as you can use threadlocal to make SimpleDateFormat thread-safe, because that class is expensive to create and each call needs to create a different instance, so it's not worth using it in a local scope. If you provide a copy of your own unique variables for each thread, you will be much more efficient. First, it reduces the number of expensive objects created by multiplexing. Second, you get thread safety without using high-cost synchronization or immutability. Another good example of thread-local variables is the Threadlocalrandom class, which reduces the number of expensive random objects created in a multithreaded environment.

18 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 operation, whether the query operation is complete and retrieving the result of operation. The result can be retrieved only when the operation is complete, and the Get method will block if the operation has not been completed. A Futuretask object can be wrapped on an object that calls callable and runnable, because Futuretask also calls the Runnable interface so it can be submitted to executor for execution.

What is the difference between interrupted and Isinterruptedd methods in 19Java?

The main difference between interrupted () and isinterrupted () is that the former clears the interrupt state and the latter does not. The Java Multi-threading interrupt mechanism is implemented with an internal identity, and calling Thread.Interrupt () to break a thread sets the interrupt ID to true. The interrupt state is zeroed when the interrupt thread calls the static method thread.interrupted () to check the break state. The non-static method, isinterrupted (), is used to query the interrupt state of other threads without changing the interrupt status identifier. Simply put, any method that throws a Interruptedexception exception will clear the interrupt state. In any case, the interrupt state of a thread can be changed by other threads calling interrupts.

20 Why are the wait and notify methods called in the synchronization 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 a race condition between wait and notify.

21 Why should you check the wait conditions in the loop?

A thread that is in a wait state may receive an error alert and a pseudo-wake, 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 cannot assume that its original wait state is still valid, and it may change after the Notify () method call and before the waiting thread wakes up. That's why using the Wait () method in a loop works better, so you can create a template in Eclipse and call wait and notify. If you want to learn more about this issue, I recommend that you read the threads and synchronization chapters in effective Java.

What is the difference between a synchronous collection in 22Java and a concurrent collection?

Both synchronous and concurrent collections provide the appropriate thread-safe collection for multithreading and concurrency, although the concurrency collection is more extensible. Before Java1.5, programmers had only synchronized sets to use and in the multi-threaded concurrency will lead to contention, hindering the system's extensibility. JAVA5 introduces concurrent collections like Concurrenthashmap, which not only provides thread safety but also improves scalability with modern technologies such as lock separation and internal partitioning.

What is the difference between heap and stack in 23Java?

Why is this problem categorized in multi-threaded and concurrent-facing questions? Because the stack is an area of memory that is closely related to threads. Each thread has its own stack memory, which is used to store local variables, method parameters, and stack calls, and variables stored in one thread are not visible to other threads. The heap is a common area of memory shared by all threads. Objects are created in the heap, in order to increase the efficiency of the thread will get a cache from the heap to its own stack, if multiple threads use the variable can cause problems, then the volatile variable can play a role, it requires the thread to read the value of the variable from main memory.

Java Thread Surface Questions

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.