Win in interview Java multithreading (11), interview java Multithreading

Source: Internet
Author: User

Win in interview Java multithreading (11), interview java Multithreading
121. 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.

 

122. 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. Each thread has a separate stack memory used to store local data.

 

123. How to Implement threads in Java?

Two Methods: 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.

 

124. What are the roles and differences between the Java keyword volatile and synchronized?

1, volatile
The modified variables do not keep copies and directly access the primary memory.
In the Java memory model, there is main memory, and each thread also has its own memory (such as registers ). For performance, a thread maintains a copy of the variable to be accessed in its own memory. In this case, the value of the same variable volume may be different from that of the memory of another thread or the value of the main memory. If a variable is declared as volatile, it means that the variable is modified by other threads at any time, so it cannot be cached in the memory of the thread.
2, synchronized

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

1. When two concurrent threads access the synchronized (this) synchronization code block of the same object, only one thread can be executed within a time period. The other thread must wait until the current thread finishes executing this code block before executing this code block.

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

3. When a thread accesses a synchronized (this) synchronization code block of the object, other threads perform synchronization on all other synchronized (this) access to the synchronization code block will be blocked.

4. When a thread accesses a synchronized (this) synchronization code block of an object, it obtains the object lock of this object. As a result, access by other threads to all the synchronized code parts of the object is temporarily blocked.

5. The above rules apply to other Object locks.

 

125. What are the different thread lifecycles?

When we create a new thread in a Java program, its status isNew.When we call the start () method of the thread, the status is changedRunnable. The thread SchedulerRunnableThe threads in the thread pool allocate CPU time and change their statusRunning.Other thread statuses includeWaiting, BlockedAndDead.

126. What is your understanding of the thread priority?

Every thread has a priority. Generally, a thread with a higher priority has a priority at runtime, but this depends on the implementation of thread scheduling, this implementation is related to the Operating System (OS dependent ). We can define the thread priority, but this does not ensure that high-priority threads will be executed before low-priority threads. The thread priority is an int variable (from 1 to 10). 1 indicates the lowest priority, and 10 indicates the highest priority.

 

127. What is a Deadlock )? How can we analyze and avoid deadlocks?

A deadlock is a situation where more than two threads are always blocked. In this case, at least two threads and more than two resources are required.

To analyze the deadlock, we need to view the thread dump of the Java application. We need to find out the threads in the status of BLOCKED and the resources they are waiting. Each resource has a unique id. With this id, we can find out which threads already have its object lock.

Avoid nested locks, use locks only as needed, and avoid waiting for an indefinite period is the usual way to avoid deadlocks.

 

128. 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.

 

129. 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

 

130. What is ThreadLocal?

ThreadLocal is used to create local variables of a thread. We know that all threads of an object will share its global variables. Therefore, these variables are not thread-safe. We can use the synchronization technology. But when we don't want to use synchronization, we can select the ThreadLocal variable.

Each Thread has its own Thread variables. They can use the get () \ set () method to obtain their default values or change their values within the Thread. ThreadLocal instances usually want them to be associated with the thread state as the private static attribute.

 

131,What is the difference between Sleep (), suspend (), and wait?

Thread. sleep () puts the current Thread in the Not Runnable state at the specified time. The thread keeps holding the monitor of the object. For example, if a thread is currently in a synchronization block or method, other threads cannot enter the block or method. If another thread calls the interrupt () method, it will wake up the "Sleep" thread.

Note: sleep () is a static method. This means that it is only valid for the current thread. A common error is the call of t. sleep () (here t is a thread different from the current thread ). Even if you execute t. sleep (), the current thread goes to sleep, not the t thread. T. suspend () is an out-of-date method. Using suspend () causes the thread to enter the stuck state. This thread will keep holding the monitor of the object, and suspend () is prone to deadlock.

Object. wait () causes the current thread to be out of the "not running" state. Unlike sleep (), wait is the object method rather than the thread. Call object. when wait () is used, the thread first needs to obtain the object lock of this object. The current thread must keep synchronizing the Lock Object and add the current thread to the waiting queue, then another thread can synchronize the same object lock to call the object. Y (), which will wake up the thread in the waiting state and then release the lock. Basically, wait ()/notify () is similar to sleep ()/interrupt (), except that the former needs to obtain the object lock.

 

132. What is a thread starved to death, and what is a live lock?

When all threads are blocked, or the required resources are invalid and cannot be processed, there is no non-blocking thread to make the resources available. The thread lock in Java API may occur in the following situations:

1. When all threads execute Object. wait (0) in the program, the parameter is 0 for the wait method. The program will send a live lock until there is a thread on the corresponding Object that calls Object. Every y () or Object. Every yall ().

2. When all threads are stuck in an infinite loop.

 

133. What is a Java Timer class? How to create a task with a specific interval?

Java. util. Timer is a tool class that can be used to schedule a thread to be executed at a specific time in the future. Timer class can be used to schedule one-time tasks or periodic tasks.

Java. util. TimerTask is an abstract class that implements the Runnable interface. We need to inherit this class to create our own scheduled task and use Timer to schedule its execution.

 

 

134. 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.

 

135. Which of the following is a better choice for Synchronous methods and synchronization blocks?

A synchronization block is a better choice because it does not lock the entire object (you can also lock the entire object ). The synchronization method locks the entire object, even if there are multiple unrelated synchronization blocks in this class, which usually causes them to stop executing and wait for the lock on the object to be obtained.

 

136. 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 ).

 

 

137. 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.

 

 

138. What is a busy cycle in multiple threads?

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. This is done to reserve the CPU cache.

In a multi-core system, a thread may run in another kernel while waiting for it to wake up. This will re-build the cache. It can be used to avoid rebuilding the cache and reduce the waiting time for reconstruction.

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.