Java face test-multithreaded article 13 __java

Source: Internet
Author: User
Tags object object thread class time interval unique id volatile
Java face test-multithreaded article 13 121, what is the 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.


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


123, how to 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, because the thread class itself is the calling runnable interface so you can inherit Java.lang.Thread class, or by calling the Runnable interface directly to override the run () method to implement the thread.


124,java keyword volatile and synchronized function and difference.

1,volatile
The variable it modifies does not retain a copy and accesses directly in the main memory.
In the Java memory model, there is main memory, and each thread has its own memory (for example, registers). For performance, a thread keeps a copy of the variable to be accessed in its own memory. This will show the same variable at some point, 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 ready to be modified by another thread, so it cannot be cache in thread memory.
2,synchronized

When it is used to modify a method or a block of code, it is possible to ensure that at most one thread at a time executes that segment of code.

First, when two concurrent threads access the synchronized (this) synchronized code block in the same object objects, only one thread can be executed at a time. Another thread must wait until the current thread finishes executing the code block before executing the code block.

Second, however, when a thread accesses a synchronized (this) synchronization code block of object, another thread can still access a non-synchronized (this) synchronized code block in that object.

Third, it is particularly critical that when a thread accesses a synchronized (this) synchronization code block of object, access to all other synchronized (this) synchronized code blocks in object is blocked by other threads.

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

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 for threads in the runnable thread pool and says their state changes to running. Other thread states are waiting,blocked and dead.

126, what is your understanding of thread priority?

Each thread is prioritized and, in general, a high-priority thread has precedence at run time, but this relies on the implementation of the thread schedule, which is related to the operating system (OS dependent). We can define the priority of the thread, 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 a deadlock (deadlock). How to analyze and avoid deadlocks.

A deadlock is a situation in which more than two threads are permanently blocked, which results in a minimum of two threads and more than two resources.

To analyze deadlocks, we need to look at the thread dumps for the Java application. We need to find those threads with blocked status and the resources they wait for. Each resource has a unique ID, and with this ID we can find out which threads already have its object lock.

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


128, what is thread-safe. is the vector a thread-safe class?

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.


How to stop a thread in 129,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 thread. 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


130, what is threadlocal?

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

Each thread has its own thread variable, which can use the Get () \set () method to obtain their default values or change their values within a thread. Threadlocal instances are typically expected to be associated with thread state as private static properties.


What is the difference between 131,sleep (), suspend () and wait ().

Thread.Sleep () causes the current thread to be in a "non-run" (not Runnable) state at a specified time. The thread always holds the object's monitor. For example, a thread is currently in a synchronized block or synchronization 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 invoke T.sleep () (where T is a thread different from the current thread). Even the execution of T.sleep () is also the current thread entering sleep rather than the t thread. T.suspend () is an obsolete method that uses suspend () to cause a thread to stagnate, which holds the object's monitor all the time, and suspend () can easily cause deadlock problems.

Object.wait () causes the current thread to be in a "non-run" state, unlike sleep (), which is a method of object rather than thread. When Object.wait () is invoked, the thread first gets the object lock of the object, the current thread must be synchronized with the lock object, the current thread is added to the wait queue, and then another thread can synchronize the same object lock to invoke Object.notify (), which wakes up the original waiting threads. 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 the thread of starvation, what is the living lock.

When all threads are blocked or cannot be processed because the resource required is not valid, non-blocking threads do not exist to make the resource available. Javaapi Centerline 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 the lines are Cheng Ka in an infinite loop.


133, what is the Java Timer class. How to create a task that has 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 scheduled with a one-time task or a cycle task.

Java.util.TimerTask is an abstract class that implements the Runnable interface, and we need to inherit this class to create our own timed tasks and use a timer to schedule its execution.



What is the difference between a synchronization set in 134,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.


135, Sync method and sync block, which is the better choice.

The sync block is a better choice because it doesn't lock the entire object (you can also lock the whole object). The synchronization method locks the entire object, even though there are multiple unrelated synchronization blocks in the class, which usually cause them to stop executing and need to wait for the lock on the object.


136, what is the thread pool. Why to 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).


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


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

In a multi-core system, a waiting thread wakes up and may run in another kernel, which rebuilds the cache. You can use it to avoid rebuilding the cache and to reduce the time it is waiting to rebuild.


Java Companion public number push Java development in some of the necessary skills, including but not limited to the database, Java Core, popular framework, management tools and server-related, at the same time for you select popular open source projects, will be the interview topics, practicing projects, high-quality video resources. Let your spare time consolidate your knowledge, unconsciously improve their development level.

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.