Thread based

The relationship between processes and threads

A thread is an entity in a process. The thread itself does not exist independently. Process is a movement activity of code in the data set, and is the basic unit of system resource allocation and scheduling. Thread is an execution path of process. There is at least one thread in a process and multiple threads in the process share the resources of the process.

The way a thread is created

Methods a

public class CusThread extends Thread{ @Override public void run() { super.run(); }}Copy the code

Way 2

public class CusRunable implements Runnable{
    @Override
    public void run() {
    }
}
Copy the code

Methods three

public class CallerTask implements Callable<String>{ @Override public String call() throws Exception { return "Hello Caller"; } } main(){ FutureTask<String> futureTask=new FutureTask<>(new CallerTask()); new Thread(futureTask).start(); try { String result=futureTask.get(); } catch (ExecutionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); }}Copy the code

The first way through class inheritance, but Java only supports single inheritance can not inherit other classes, task and code are not separated, multiple threads to perform the same task requires multiple copies of task code.

The second way through the Runable interface is less restrictive than the first.

The third method has a return value, and calls the GET method to poll the result internally.

Thread-dependent behavior

wait()

When a thread calls wait() on a shared variable, the calling thread blocks until one of the following events occurs: (1) Other threads have called notify() or notifyAll() on the shared object; (2) Other threads have called interrupt() on the shared object. The thread throws InterruptedException.

In addition it is important to note that if the call wait () method of thread without prior access to the object of the monitor lock, call the wait () method called when the thread will be thrown IllegalMonitorStateException anomalies

wait(long timeout)

This method has one more timeout parameter than wait(), which is different in that if a thread calling this method on a shared object suspends, If no thread has invoked the shared variable’s notityAll() or notityAll() method within the specified timeout ms, the function will still return as a result.

notity()

A thread calling the notity() method of a shared object wakes up a thread that has been suspended after calling the WAIT series of methods on that shared variable. Multiple threads may be waiting on a shared variable, and it is random which waiting thread is woken up.

notityAll()

Unlike calling notity() on a shared variable, which wakes up a thread that is blocked on the shared variable, the notityAll() method wakes up all threads that were suspended on the shared variable due to calls to the Wait series of methods.

join()

In the case of multi-threading, thread execution can be ordered through join() method. One thread is blocked after calling the join method, waiting for the thread to return the order to execute the next thread calling the Join () method.

sleep()

The Thread class has a static sleep method. When an executing Thread calls the Thread’s sleep method, the calling Thread temporarily cedes execution rights for a specified period of time, i.e. does not participate in CPU scheduling. However, the Thread’s monitor resources, such as locks, are still held. When the specified sleep time is up, the function returns normally, the thread is in the ready state, and then participates in CPU scheduling. After obtaining CPU resources, the thread can resume running.

yield()

The Thread class has a static yield method. When a Thread calls yield, it signals the Thread scheduler that the current Thread is requesting its CPU usage.

interrupted()

Thread interrupt is a cooperative mode between threads in Java. The execution of the thread cannot be terminated directly by setting the interrupt flag of the thread. Instead, the interrupted thread handles the interrupt status by itself.

Thread context switch

Number of threads in a multithreaded programming, is generally greater than the number of CPU, and can only be used by one thread per CPU the same time, in order to make the user feel when multiple threads at the same time, the allocation of CPU resources using the time slice rotation policy, also is to give each thread allocate a time slice, thread CPU to perform the task in time. When the current thread runs out of time slices, it becomes ready and cedes the CPU to another thread. This is called a context switch, where it switches from the context of the current thread to another thread.

A deadlock

Deadlock refers to the process in which two or more threads are waiting for each other because of competing for resources. Without external force, these threads will wait for each other and cannot continue to run.

Four conditions for deadlocks

Mutually exclusive: A thread uses a resource that has been acquired exclusively, that is, only one thread occupies the resource at the same time. If another thread requests the resource at this point, the requester can only wait until the thread holding the resource releases the resource.

Request and hold condition: a thread that has already held at least one resource makes a request for a new resource, but the new resource has been occupied by another thread. Therefore, the current thread is blocked, but the blocked thread does not release the acquired resource.

Inalienable condition: A thread cannot preempt a resource until it uses it up. The thread releases the resource only after it uses it up.

Loop waiting condition: when deadlock occurs, there must be a thread-resource ring chain, i.e. Thread set {T0,T1,T2… T1 is waiting for a resource TO be occupied by T2… Tn is waiting for resources to be occupied by T0.

Daemon threads versus user threads

There are two types of threads in Java: daemon threads and user threads. The main function is called when the JVM starts. The main thread is a user thread, and several daemons, such as the garbage collector thread, are also started inside the JVM.

The difference between daemon threads and user threads

The JVM exits normally when the last non-daemon thread terminates, regardless of whether there is currently a daemon thread, meaning that the JVM exits regardless of whether the daemon thread terminates.

Concurrent parallelism concept

Concurrency: Multiple tasks are executed at the same time in the same period.

Parallel: Multiple tasks are executed simultaneously per unit of time.

Shared resource: a resource is owned or accessed by multiple threads.

Thread-safety problem: Thread-safety problem refers to the problem of dirty data or other unforeseeable results when multiple threads write to a shared resource at the same time without any synchronization.

Synchronized: An atomic internal lock provided by Java that can be used by every object in Java as a synchronized lock. These internal locks that cannot be seen by Java’s built-in users are called internal locks, also called monitor locks. The thread’s executing code automatically acquires an internal lock before entering a synchronized block, which is blocked and suspended when accessed by other threads.

The syschronized keyword causes a thread context switch and a thread scheduling overhead

Why does synchronized cause a thread context switch

Since threads in Java correspond to native threads of the operating system one by one, when a thread is blocked, it needs to switch from user mode to kernel mode to perform blocking operation, which is a time-consuming operation, and the use of synchronized will lead to context switch.

Volatile: Java provides a weak form of synchronization. This keyword ensures that updates to one variable are immediately visible to other threads.

Scenarios where volatile is used

  1. When a variable value is written independent of its current value. Because if you rely on the current value, the three steps of calculating and writing are not atomic, and volatile does not guarantee atomicity.
  2. Reading and writing variable values without locking. Since locking itself guarantees memory visibility, there is no need to declare variables volatile.

CAS (Compare And Swap)

** CAS :** Non-blocking atomic operations provided by the JDK, which hardware guarantees atomicity for comparison and update operations.

The lock

Pessimistic lock: Pessimistic lock refers to the conservative attitude of data modification, believing that data can be easily modified by other threads, so the data is accelerated before being processed, and the data is locked during the whole process.

Optimistic lock: Optimistic lock is compared to pessimistic lock. It believes that data will not cause conflicts in general, so it will not add exclusive locks before accessing records. Instead, it will formally detect whether data conflicts are detected when data is submitted for update.

Fair lock: Indicates that the order in which a thread acquires a lock is determined by the time the thread requests the lock. (Fair locking incurs performance overhead)

Unfair lock: Lock acquired at runtime, i.e., first come, not first served.

Exclusive locks: Exclusive locks ensure that only one thread can obtain the lock at any time (for example, ReentrantLock). Exclusive locks are pessimistic locks, and each access to a resource is coupled with a mutex, limiting concurrency

Shared lock: A shared lock can be held by multiple threads at the same time (for example, ReadWriteLock read/write lock shared lock). A shared lock is an optimistic lock.

Reentrant lock: A thread that acquires an exclusive lock held by another thread and does not block is a synchronized lock. A reentrant lock maintains a thread identifier inside the lock.

Spin lock: When a thread obtains a lock and finds that the lock is already owned by another thread, it does not block immediately. Multiple attempts to acquire the lock (the default number is 10) without giving up CPU usage are likely to be followed by subsequent attempts by other threads to release the lock. The current thread is blocked and suspended if the lock is not acquired after a specified number of attempts.