What is a thread?
Thread is the smallest unit that the operating system can schedule operations. It is contained in the process and is the actual operating unit in the process. It allows programmers to do multiprocessor programming, and you can use multithreading to speed up computationally intensive tasks. For example, if it takes 100 milliseconds for one thread to complete a task, then it takes 10 threads to complete the task in 10 milliseconds.
What is the difference between threads and processes?
Threads are a subset of processes, and a process can have many threads, each performing different tasks in parallel. Different processes use different memory space, and all threads share the same memory space. Each thread has its own stack memory to store local data.
How to implement threads in Java?
Two ways: An instance of the java.lang.Thread class is a Thread but it needs to call the Java.lang.Runnable interface to execute, Since the Thread class itself is called the Runnable interface, you can either inherit the java.lang.Thread class or override the run() method directly by calling the Runnable interface to implement the Thread.
Java keyword volatile and synchronized function and difference?
1, volatile
The variables it modifies do not retain copies and access main memory directly.
In the Java memory model, there is main Memory, and each thread has its own memory (such as registers). For performance, a thread keeps a copy of the variable to be accessed in its own memory. In this case, the value of the same variable in memory in one thread may be inconsistent with the value in memory in another thread or in main memory at any given moment. Declaring a variable volatile means that it is subject to modification by other threads and therefore cannot be cached in thread memory.
2, the synchronized
When it is used to decorate a method or a code block, it ensures that at most one thread is executing the code at a time.
① When two concurrent threads access the synchronized(this) block of the same object, only one thread can be executed at a time. Another thread must wait for the current thread to finish executing the code block before executing it.
② However, when one thread accesses a synchronized(this) block of an object, another thread can still access the non-synchronized (this) block of that object.
③ In particular, when one thread accesses a synchronized(this) block of an object, access to all other synchronized(this) blocks in the object is blocked by other threads.
④ When a thread accesses a synchronized(this) block of an object, it acquires the object lock. As a result, access by other threads to all synchronized code parts of the object is temporarily blocked.
⑤, the above rules are also applicable to other object locks.
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 the threads in the Runnable thread pool and changes their state to Running. Other thread states include Waiting, Blocked, and Dead.
What do you understand about thread priority?
Each thread has priority. Generally speaking, threads with higher priority have priority at run time, but this depends on the implementation of thread scheduling, which is OS dependent. We can define the priority of a thread, but this does not guarantee that a higher-priority thread will execute before a lower-priority thread. Thread priority is an int variable (1-10), with 1 representing the lowest priority and 10 representing the highest priority.
What is a Deadlock? How to analyze and avoid deadlocks?
A deadlock is a condition in which more than two threads are permanently blocked, resulting in the need for at least two more threads and two more resources.
To analyze deadlocks, we need to look at thread dumps for Java applications. We need to identify the threads whose state is BLOCKED and the resources they are waiting for. Each resource has a unique ID that we can use to find out which threads already own its object lock.
Avoiding nested locks, using locks only where they are needed, and avoiding waiting indefinitely are common ways to avoid deadlocks.
What is thread safety? Is Vector a thread-safe class?
If your code is in a process that has multiple threads running at the same time, those threads may be running the code at the same time. If the result of each run is the same as the result of a single thread run, and the values of other variables are the same as expected, it is thread-safe. The same instance object of a thread-safe counter class can be used by multiple threads without miscalculation. Obviously you can split collection classes into two groups, thread-safe and non-thread-safe. Vector is thread-safe using a synchronous approach, whereas ArrayList, like it, is not thread-safe.
How to stop a thread in Java?
Java provides a rich API but not one for stopping threads. JDK 1.0 originally had control methods like stop(), suspend(), and resume(), but they were deprecated in subsequent JDK releases due to potential deadlock threats, and the designers of the Java API did not provide a compatible, thread-safe way to stop a thread. The thread terminates automatically when the run() or call() methods have finished executing. To terminate a thread manually, you can use volatile booleans to exit the run() loop or cancel the task to interrupt the thread
What is ThreadLocal?
ThreadLocal is used to create ThreadLocal variables. 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, and they can use the get()set() method to get their default value or change their value internally. ThreadLocal instances typically expect them to be associated with thread state as private static properties.
What is the difference between Sleep(), suspend(), and wait()?
Thread.sleep() causes the current Thread to be in a “Not Runnable” state for the specified time. The thread always holds the monitor of the object. For example, if a thread is currently in a synchronized block or method, other threads cannot enter that 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 it is valid only for the current thread, and a common mistake is to call t.sleep(), (where t is a different thread from the current thread). Even when t.sleep() is executed, the current thread goes to sleep, not the T thread. Suspend () is an outdated method that uses suspend() to cause a thread to enter a standstill state, and suspend() is prone to deadlock problems.
Object.wait () makes the current thread “unrunnable”. Unlike sleep(), wait is an object method, not a thread. When calling Object.wait (), the thread obtains the object lock on the object. The current thread must synchronize the lock on the object and add the current thread to the wait queue. Another thread can then synchronize the same object lock to call Object.notify (), which will wake up the original waiting thread and release the lock. Basically wait()/notify() is similar to sleep()/interrupt() except that the former requires an object lock.
What is thread starvation and what is live lock?
When all threads are blocked, or cannot be processed because the required resource is invalid, there are no non-blocking threads to make the resource available. Thread live locks in the JavaAPI can occur in the following situations:
1, when all threads execute object.wait (0) in the program, wait method with argument 0. The program will issue a live lock until a thread calls Object.notify() or Object.notifyall () on the corresponding Object.
2. When all threads are stuck in an infinite loop.
What is the Java Timer class? How do I create a task with a specific time interval?
Java.util. Timer is a utility 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-off 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 schedule its execution using a Timer.
What is the difference between synchronous and concurrent collections in Java?
Both synchronous and concurrent collections provide suitable thread-safe collections for multithreading and concurrency, although concurrent collections are more extensible.
Prior to Java1.5, programmers had only synchronous collections to use and contention was caused when multiple threads were running concurrently, hindering system scalability.
Java5 introduces concurrent collections like ConcurrentHashMap, which not only provide thread safety but also improve scalability with modern techniques such as lock separation and internal partitioning.
15. Which is the better choice, synchronization method or synchronization block?
A synchronized block is a better choice because it doesn’t lock the whole object (although you can make it lock the whole object). Synchronized methods lock the entire object, even if there are multiple unrelated synchronized blocks in the class, which usually causes them to stop executing and wait to acquire the lock on the object.
What is a thread pool? Why use it?
Threads are expensive to create in terms of resources and time, the response time can be slow if the task comes in, and the number of threads a process can create is limited.
To avoid these problems, a number of threads are created at program startup to respond to processing. These threads are called thread pools, and the threads inside are called worker threads.
Starting with JDK1.5, the Java API provides an 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 suitable for a program with many short-lived tasks).
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 rather than the event distributor thread. InvokeAndWait() updates GUI components synchronously, such as a progress bar, and changes the progress bar once the progress is updated. If progress is being tracked by multiple threads, the invokeAndWait() method is called to request the event dispatcher thread to update the component accordingly. The invokeLater() method calls the update component asynchronously.
What are busy loops in multithreading?
A busy loop is one in which a programmer uses a loop to make a thread wait. Unlike the traditional methods wait(), sleep(), or yield(), which give up CPU control, a busy loop does not give up CPU. It simply runs an empty loop. This is done to preserve the CPU cache.
In multi-core systems, a waiting thread may be running in another kernel when it wakes up, which rebuilds the cache. It can be used to avoid rebuilding the cache and reduce waiting time for rebuilding.
What is the Java memory model?
The Java memory model specifies and guides the deterministic behavior of Java programs across memory architectures, cpus, and operating systems. This is especially important in the case of multithreading. The Java memory model provides a guarantee that changes made to one thread can be seen by other threads, and that they are antecedent. This relationship defines rules that allow programmers to think more clearly about concurrent programming. For example, having sex first ensures that:
Code in a thread can be executed in sequence, which is called the program order rule.
For the same lock, one unlock operation must take place after another lock operation, also known as pipe lock rule.
A previous write to volatile before a subsequent read from volatile. Also known as a volatile variable rule.
Any operation within a thread must be followed by a start() call from that thread, also known as the thread start rule.
All operations of a thread are terminated before the thread terminates.
Finalization of an object must occur after the object is constructed. Also called object finalization rule.
Can be delivered
What is the difference between interrupted and isInterruptedd in Java?
The main difference between interrupted() and isInterrupted() is that the former clears the interrupted state while the latter does not. The interrupt mechanism for Java multithreading is implemented with an internal identifier. Calling thread.interrupt () to interrupt a Thread sets the interrupt identifier to true. The interrupted status is cleared when the interrupted Thread calls the static method thread.interrupted () to check the interrupted status.
The non-static method isInterrupted() is used to query the interrupted status of other threads without changing the interrupt status identifier. Simply put, any method that throws InterruptedException clears the interrupted status. In any case, the interrupt status of one thread can be changed by other threads calling interrupts.
What is the difference between synchronous and concurrent collections in Java?
Both synchronous and concurrent collections provide suitable thread-safe collections for multithreading and concurrency, although concurrent collections are more extensible. Prior to Java1.5, programmers had only synchronous collections to use and contention was caused when multiple threads were running concurrently, hindering system scalability. Java5 introduces concurrent collections like ConcurrentHashMap, which not only provide thread safety but also improve scalability with modern techniques such as lock separation and internal partitioning.
Both synchronous and concurrent collections support thread-safety, and the main differences between them are performance and scalability, as well as how they implement thread-safety.
Synchronize HashMap, Hashtable, HashSet, Vector, and ArrayList compared to their concurrent implementations (ConcurrentHashMap, CopyOnWriteArrayList, CopyOnWriteHashSet) is much slower. The main reason for this slowness is locking. Synchronized collections lock up the entire Map or List, while concurrent collections do not. Concurrent collections achieve thread-safety by using advanced and mature techniques like lock stripping.
For example, ConcurrentHashMap divides the entire Map into several segments, locks only the related segments, and allows multiple threads to access other segments that are not locked.
Similarly, CopyOnWriteArrayList allows multiple threads to read asynchronously, making a copy of the entire List when a thread writes to it.
If you use concurrent collections under conditions that favor concurrent collections when you read more and write less, this will be more scalable than using synchronous collections.
What is a thread pool? Why use it?
Threads are expensive to create in terms of resources and time, the response time can be slow if the task comes in, and the number of threads a process can create is limited. To avoid these problems, a number of threads are created at program startup to respond to processing. These threads are called thread pools, and the threads inside are called worker threads. Starting with JDK1.5, the Java API provides an 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 suitable for a program with many short-lived tasks)
The function of the thread pool is to initialize a certain number of threads when the thread is called. When the wired program comes, it checks whether the initialized thread is empty or not, and then sees whether the number of threads currently running has reached the maximum number. If not, it allocates a new thread to deal with it.
Just like eating in a restaurant, call out a waiter from inside; However, if the maximum number has been reached, it is equivalent to running out of servers, and there is no way to do that, other threads have to wait until a new “server” is available.
The advantage of a thread pool is that it manages threads and has a high hub so that programs don’t mess up and the system doesn’t fail due to insufficient resources due to a large number of concurrent applications.
What is the difference between live locks and deadlocks in Java?
Live lock: A thread usually has activities that respond to other threads. If other threads respond to another thread’s activity, it is possible to issue live locks. As with deadlocks, threads that issue live locks cannot continue execution. However, the threads aren’t blocking — they’re too busy responding to each other to resume work. This is the equivalent of two people meeting in a corridor: one leans to his left to let him pass, while the other leans to his right to let him pass. So they’re blocking each other. One leans to his right and the other leans to his left, and they still block each other.
Deadlock: Two or more threads are blocking a lock that is held by another thread in a deadlock state. Deadlocks usually occur when multiple threads request the same set of locks at the same time, but in different order. Deadlocks cause your program to hang and fail to complete its task.
How to avoid deadlocks?
The following four conditions must be met for a deadlock to occur:
Mutually exclusive condition: a resource can only be used by one process at a time.
Request and hold conditions: when a process is blocked by requesting resources, it holds on to acquired resources.
Non-dispossession condition: a process cannot forcibly take away a resource it has acquired until it is used up.
Circular waiting condition: a circular waiting resource relationship is formed between several processes.
Two techniques are used to avoid deadlocks:
Lock order (threads lock in a certain order)
Lock duration (when a thread tries to acquire a lock, it will give up the lock request and release the lock it owns)
What is the difference between notify and notifyAll?
1. Notify () and notifyAll() are methods that Object objects use to notify the threads waiting for the Object.
2, void notify(): wakes up a thread waiting for this object.
Void notifyAll(): wakes up all threads waiting for the object.
The biggest difference between the two is:
NotifyAll Causes all threads waiting to be notified on an object to exit the wait state and become locks waiting on the object. Once the object is unlocked, they compete.
When the first thread is finished, the lock on the object is released. If the object does not use the notify statement again, even if the object is idle, the lock on the object is released. Threads waiting in wait wait until the object emits a notify or notifyAll. They wait to be notified or notifyAll instead of locking.
What is a ReentrantLock?
Java. Util. Concurrent. Lock the lock framework is an abstraction to lock, it allows the realization of the lock as a Java class, rather than as a language feature. This leaves room for multiple 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 voting, timed Lock waiting, and interruptible Lock waiting. In addition, it provides better performance in cases of intense contention. (In other words, when many threads want to access a shared resource, the JVM can spend less time scheduling threads and more time executing threads.)
What does a Reentrant lock mean? In simple terms, it has an acquisition counter associated with the lock, and if one of the threads that owns the lock gets it again, the acquisition counter is incremented by one, and then the lock needs to be released twice for it to actually be released. This mimics the semantics of synchronized; If a thread enters a synchronized block protected by a monitor it already owns, the thread is allowed to continue. When a thread exits a second (or subsequent) synchronized block, the lock is not released, except when the thread exits the first synchronized block protected by the monitor it entered. Before releasing the lock.
27. What application scenarios can read/write locks be used in?
Read/write locks can be used in read/write scenarios. Multiple read operations can be performed concurrently by only one thread
ReadWriteLock optimizes cases where relatively infrequent writes are made to a data structure, but multiple tasks frequently read the data structure. ReadWriteLock allows you to have multiple readers at the same time, as long as none of them attempt to write. If the write lock is already held by another task, no reader can access it until the write lock is released.
ReadWriteLock improves application performance by several factors:
1. The result of comparing the frequency of data being read with the frequency being modified.
2. Read and write times
3. How many threads are contending
4. Whether to run on a multiprocessing machine