One, 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.
Ii. 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.
Third, 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, 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.
Four, the Java keyword volatile and synchronized role 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.
①, 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.
②, 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) synchronization code block in the object.
③, 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 of this object. As a result, other threads are temporarily blocking access to all of the synchronization code portions of the object.
⑤, the above rules also apply to other object locks.
V. What are the different thread life cycles?
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.
Vi. 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.
Vii. What is a 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.
Viii. 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.
Ix. 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 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
Ten, 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.
What is the difference between Xi. 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.
12. What is a thread starved and 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.
13. 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.
14. What is the difference between synchronous collections in Java and concurrent collections?
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 better choice, the synchronization method and the synchronization block?
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.
16. 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).
17. What is the difference between invokeandwait and Invokelater in 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.
18. What is a 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.
19. 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 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
20. What is the difference between interrupted and Isinterruptedd methods in Java?
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.
A 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.
21. What is the difference between synchronous collections in Java and concurrent collections?
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.
Whether it's synchronous collections or concurrent collections they all support thread safety, and the main differences between them are performance and scalability, and how they implement thread safety.
Synchronous HashMap, Hashtable, HashSet, Vector, ArrayList compared to their concurrent implementations (Concurrenthashmap, Copyonwritearraylist, Copyonwritehashset) is much slower. The main cause of this slowness is the lock, which locks the entire map or list, while the concurrent collection does not. Concurrent collections implement thread safety by using advanced and sophisticated techniques like lock stripping.
For example, Concurrenthashmap will divide the entire map into fragments, lock only the relevant fragments, and allow multiple threads to access other unlocked fragments.
Similarly, Copyonwritearraylist allows multiple threads to read in an unsynchronized manner, and when the thread is written it copies the entire list to it.
This can be more scalable than using synchronous collections if you are using concurrent collections under conditions that are beneficial to concurrent collections, such as read more write less.
22. 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)
The role of the thread pool is to initialize a certain number of threads at the time the thread is called, and when the thread comes over, it detects that the initialized threads are empty, and does not see whether the number of threads currently running has reached the maximum number, and if not, a new thread is allocated for processing.
Just like eating in a restaurant, call a waiter out of the house, but if you have reached the maximum number, it is equivalent to the waiter has been exhausted, there is no way, the other thread will only wait until there is a new "waiter" so far.
The advantage of the thread pool is that it can manage threads and have a high hub so that the program does not mess up and that the system will not be hung up because of a lot of concurrency and insufficient resources.
23. What is the difference between a live lock and a deadlock in Java?
Live Lock: A thread typically has activities that respond to other threads. If other threads also respond to the activity of another thread, a live lock can occur. As with a deadlock, the thread that made the life lock cannot continue execution. threads, however, are not blocked-they are busy responding to the other person's inability to resume work. This is the equivalent of two people who meet in the corridor: A to his own left by want to let B past, and B to his right side by want of a past. It is visible that they have blocked each other. A to his right, and B to his left, they still blocked the other side.
Deadlock: Two or more threads block locks that are held by threads waiting for other deadlock states. Deadlocks usually occur when multiple threads are simultaneously requesting the same set of locks in different order, and deadlocks can cause your program to hang without completing the task.
24, how to avoid deadlocks?
The following four conditions must be met for a deadlock to occur:
Mutex condition: A resource can only be used by one process at a time.
Request and hold condition: When a process is blocked by a request for resources, it remains in place for the resources that have been obtained.
Non-deprivation: the resources that the process has acquired cannot be forcibly stripped until the end of use.
Cyclic wait condition: a cyclic waiting resource relationship is formed between several processes.
There are two techniques for avoiding deadlocks:
Lock order (threads locking in a certain order)
Lock time limit (when a thread attempts to acquire a lock with a certain time limit, the request for the lock is discarded and the lock is freed)
25. What is the difference between notify () and Notifyall ()?
Both 1,notify () and Notifyall () are methods that object objects are used to inform the thread that is waiting for the object.
2,void notify (): Wakes up a thread that is waiting for the object.
3,void Notifyall (): Wakes up all threads that are waiting on the object.
The biggest difference between the two is:
Notifyall causes all threads that originally wait on the object to be notify to exit the wait state, becoming a lock on the object, and once the object is unlocked, they compete.
Notify he just chooses a wait-state thread to notify, and it gets the lock on the object, but does not disturb other threads that are also waiting to be notify by the object, releasing the lock on the object when the first thread finishes running, and if the object does not use the Notify statement again, Even if the object is idle, the other waiting-state waits for the thread to remain in the wait state until it emits a notify or notifyall, and waits for a notify or notifyall instead of a lock, because the object is not notified.
26. What is a reentrant lock (reentrantlock)?
The lock framework in Java.util.concurrent.lock is an abstraction of locking, which allows the implementation of a lock to be implemented as a Java class, rather than as a language feature. This leaves space for the various implementations of lock, which may have different scheduling algorithms, performance characteristics, or locking semantics. The Reentrantlock class implements lock, which has the same concurrency and memory semantics as synchronized, but adds features like lock polling, timed lock-in, and interruptible lock waiting. In addition, it provides better performance in the case of intense contention. (In other words, when many threads are trying to access a shared resource, the JVM can spend less time dispatching the thread and more of it to the execution thread.) )
What does the reentrant lock mean? Simply put, it has a lock-related get counter, if one of the threads that owns the lock gets the lock again, then the fetch counter increases by 1, and then the lock needs to be freed two times to get a true release. This mimics the semantics of synchronized; If a thread enters a synchronized block that is protected by a monitor that the thread already owns, it allows the thread to continue and does not release the lock when the thread exits the second (or subsequent) synchronized block. The lock is released only when the thread exits the first synchronized block that the monitor protects when it enters.
27. What are the application scenarios for reading and writing locks?
Read-write locks can be used for "read and write less" scenarios, read and write locks support multiple read operations concurrently, and write operations can only be performed by a single thread
Readwritelock is optimized for situations where data structures are written relatively infrequently, but there are multiple tasks that are frequently read by this data structure. Readwritelock allows you to have multiple readers at the same time, as long as they are not trying to write. If a write lock is already held by another task, no reader can access it until the write lock is released.
Readwritelock the improvement of program performance is mainly subject to the following factors:
1, the frequency at which the data is read is compared with the modified frequency.
2, read and write time
3, how many threads are competing
4, whether to run on a multi-processing machine
Written in the end: Welcome message discussion, welcome attention, Continuous Update!
Ali P8 Architect summarizes Java concurrency test questions (featured)