Win in the interview Java Multithreading (11)

Source: Internet
Author: User
Tags thread class unique id volatile

121, 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.

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

123, how do I implement threads in Java?

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

124,java keyword volatile and synchronized action and difference?

1,volatile
The variable it modifies does not retain the copy and accesses the main memory directly.
In the Java memory model, there are main memories, and each thread has its own memory (for example, a register). For performance, a thread keeps a copy of the variable to be accessed in its own memory. This will cause the same variable to appear in a moment when the value in the memory of one thread may be inconsistent with the value in the memory of another thread, or the value in main memory. A variable declared as volatile means that the variable is modified by other threads at any time, so it cannot be cache in the thread memory.
2,synchronized

when it is used to decorate a method or a block of code, it is guaranteed that at most one thread at a time executes the code.

First, when two concurrent threads access the same object in the synchronized (this) synchronization code block, only one thread can be executed within a single time. The other thread must wait for the current thread to finish executing the block before it can execute the code block.

Second, however, when a thread accesses one synchronized (this) of an object to synchronize a block of code, another thread can still access the non-synchronized (this) synchronous code block in the object.

Third, in particular, when a thread accesses one synchronized (this) of an object to synchronize a block of code, other threads will block access to all other synchronized (this) synchronization blocks in object.

When a thread accesses a synchronized (this) of an object to synchronize a block of code, it obtains the object lock for that object. As a result, other threads are temporarily blocking access to all of the synchronization code portions of the object.

The above rules apply to other object locks as well.

125, what are the different thread lifecycles?

When we create a new thread in a Java program, its state is new. when we call the thread's start () method, the state is changed to Runnable. The thread scheduler allocates CPU time to threads in the Runnable thread pool and says their state changes to Running. Other thread states also have waiting,blocked and Dead.

126, what is your understanding of thread priorities?

Each thread has a priority, in general, a high-priority thread will have priority at run time, but this depends on the implementation of the thread schedule, which is operating system-related (OS dependent). We can define the priority of threads, but this does not guarantee that high-priority threads will be executed before the low-priority thread. The thread priority is an int variable (from 1-10), 1 represents the lowest priority, and 10 represents the highest priority.

127, what is the deadlock (Deadlock)? How do I analyze and avoid deadlocks?

Deadlocks are situations in which more than two threads are permanently blocked, which results in a minimum of two threads and more than two resources.

Parsing deadlocks, we need to look at thread dumps for Java applications. We need to identify the threads that are blocked and the resources they wait for. Each resource has a unique ID, which we can use to find out which threads already have their object locks.

Avoiding nested locks, using locks only where needed and avoiding waiting indefinitely is the usual way to avoid deadlocks.

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

How do I stop a thread in a 129,java?

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

130, what is threadlocal?

Threadlocal is used to create local variables for threads, we know that all threads of an object share its global variables, so these variables are not thread-safe and we can use synchronous technology. But when we don't want to use synchronization, we can choose the threadlocal variable.

Each thread will have their own thread variable, which can use the Get () \set () method to get their default values or change their values inside the thread. Threadlocal instances are typically the private static property that you want them to associate with the thread state.

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

Thread.Sleep () causes the current thread to be in a non-running (not Runnable) state at the specified time. The thread has been holding the object's monitor. For example, a thread is currently in a synchronous block or synchronous method, and other threads cannot enter the block or method. If another thread calls the interrupt () method, it wakes up the "sleeping" thread.

Note: Sleep () is a static method. This means that only the current thread is valid, and a common mistake is to call T.sleep (), where T is a different thread than the current thread. Even if T.sleep () is executed, the current thread goes to sleep, not the t thread. T.suspend () is an obsolete method that uses suspend () to cause a thread to go into a stagnant state, which will hold the object's monitor all the time, and suspend () can cause a deadlock problem.

Object.wait () makes the current thread out of a "non-operational" state, unlike sleep () where wait is the method of object instead of thread. When calling Object.wait (), the thread first acquires an object lock on the object, the current thread must remain in sync on the lock object, add the current thread to the wait queue, and then another thread can synchronize the same object lock to invoke Object.notify (), which will wake up the threads in the original wait. Then release the lock. Basically wait ()/notify () is similar to sleep ()/interrupt (), except that the former needs to acquire an object lock.

132, what is a thread starved, what is a live lock?

Non-blocking threads make resources available when all threads are blocked, or because the required resources are invalid and cannot be processed. Javaapi midline Cheng locks can occur in the following situations:

1, when all threads execute object.wait (0) in the program, the wait method with a parameter of 0. The program will have a live lock until the thread calls Object.notify () or Object.notifyall () on the corresponding object.

2, when all lines measuring modules in an infinite loop.

133, what is the Java Timer class? How do I create a task with a specific time interval?

Java.util.Timer is a tool class that can be used to schedule a thread to execute at a specific time in the future. The 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, and we need to inherit the class to create our own timed task and use the timer to schedule its execution.

What is the difference between a synchronous collection in 134,java 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.

135, synchronization method and synchronization block, which is the better choice?

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

136, what is a thread pool? Why use it?

Creating threads takes expensive resources and time, and if the task is to create a thread, the response time is longer and the number of threads a process can create is limited.

To avoid these problems, when the program starts, it creates several threads that respond to processing, called the thread pool, which is called a worker thread.

Starting with JDK1.5, the Java API provides a executor framework that allows you to create different thread pools. For example, a single thread pool, one task at a time, a fixed number of thread pools or a pool of cache threads (an extensible thread pool for programs that are suitable for many short-lived tasks).

What is the difference between invokeandwait and Invokelater in 137,java?

These two methods are provided by the swing API to Java developers to update GUI components from the current thread instead of the event dispatch thread. Invokeandwait () updates the GUI component synchronously, such as a progress bar, and once the progress is updated, the progress bar is changed accordingly. If the progress is tracked by multiple threads, call the Invokeandwait () method to request the event dispatch thread to update the component accordingly. The Invokelater () method is called to update the component asynchronously.

138, what is the busy loop in multi-threading?

A busy loop is when a programmer uses a loop to wait for a thread, unlike the traditional method wait (), sleep () or yield (), which discards CPU control, and the busy loop does not abandon the CPU, it is running an empty loop. This is done to preserve the CPU cache.

In multicore systems, one waiting thread wakes up and may run in another kernel, which rebuilds the cache. It can be used to avoid rebuilding the cache and reducing the time it takes to wait for a rebuild.

Win in the interview Java Multithreading (11)

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.