What is a Java thread?

A running program is a process, and a process can have multiple threads (threads are the smallest unit of program execution).

Methods to start a Java thread

1. FutureTask implements the Callable interface, overrides the Call method, and implements the thread that has returned the result to spin to wait for completion or exception through the spin GET method

2, inherit Thread, override run method

3, implement Runnable, override the run method

ThreadPoolExecutor

What is the purpose of using threads?

1, multi-core CPU scenario, truly realize parallel computing, 2, improve program throughput, maximize the use of hardware performance. 3. Asynchronous processing

What are the benefits of using threads?

1. In an application process, there will be multiple tasks executed at the same time. By creating different threads for different tasks, the real-time processing of the program can be improved and the program throughput can be improved. 2, make full use of the characteristics of CPU multi-core, maximize the use of hardware performance capabilities 3, by enabling thread asynchronous processing, improve the corresponding speed, improve the user experience of the program.

5. Thread usage scenarios

BIO model optimization (ONE thread is required for a connection in BIO, which is expensive), file batch running, complex business processing, middleware enabling background thread cleaning resources, scheduled tasks, etc

Java thread running process, state?

In the Thread class, six states are defined

public enum State {
        NEW,
        RUNNABLE,
        BLOCKED,
        WAITING,
        TIMED_WAITING,
        TERMINATED;
    }
Copy the code

Various status code demonstrations:

Thread. Sleep (n) state, TIMED_WAITING state

If object.wait (n), TIMED_WAITING

Both threads compete for the same lock, successfully enter sleep timed_waiting, and fail to enter blocked

Finally, draw the flow of the state diagram

The question here: What does thread.sleep (0) do? The thread immediately resumes running object.wait (0) with the same effect as object.wait (n).

How do Java threads stop correctly?

1. Thread.stop, the JDK’s official method for forcing threads to stop, breaks the data integrity of a program by releasing all locked monitor objects. If any objects previously protected by these monitors are in an inconsistent state, the corrupted objects will be visible to other threads, potentially resulting in arbitrary behavior. Thread.interrupt() can be used to set an interrupt flag for a Thread, and then loop through the program to determine whether the interrupt status is set to true.

Interrupt () is a native method for Thread interrupt(). JVM implementations are as follows:

3. Let’s look at the correct way to stop a thread that is executing:

4. How to stop a thread if it is sleeping?

5. Verify that the park method is also interrupted by the interrupt method

Summary: It is recommended to interrupt a thread with interrupt. Sleep/Park threads can also respond to interrupt requests.

Wait yield sleep notify/notifyall

sleep()

Sleep () method you need to specify the waiting time, enter a state of waiting, it can make the currently executing thread (note here) suspended within the specified time, enter the blocking state, this method not only can let the other with priority or higher priority thread to get the opportunity to perform also lets get the chance to perform low priority thread. However, the sleep() method does not release the lock flag, which means that if a synchronized block is present, other threads still cannot access the shared data. If the thread is interrupted, it responds with an interrupt exception and stops sleeping. Sleep causes currently executing threads to sleep (temporarily stop) for a specified period of time, according to the system timer and scheduler. The thread will not lose any ownership of the monitor, and resuming execution will depend on scheduling and availability of the processor executing the thread.

The cache of write data is not loaded from the register to the shared memory until sleep is called, nor is the cache of the register reloaded after sleep is called

wait()

Wait () differs from sleep() in that it releases the object’s “lock flag” and causes the thread to block,blocking.

Wait (), notify(), and notifyAll() can only be used in synchronized statements, but how do you achieve these effects with ReentrantLock? The solution is to use already. NewCondition () to obtain a class object Condition, then the Condition of await (), signal () and signalAll () corresponding to the three methods above.

Call the wait method (release the synchronization lock), which causes the current thread to enter the wait pool wait set of the current object, and to abandon the synchronization lock resource of the current object, and enter the wait state of monitor until the following situation occurs: Other threads call notify and are selected to be awakened. Other threads call notifyAll. Some threads interrupt the current thread, Thread#interrupt()

notify()

Randomly wakes up a thread that is waiting for monitor on that object

notifyAll()

Wake up all threads that are waiting for Monitor on this object to repreempt the lock.

yield()

Giving up CPU resources does not release object locks

join()

The join() method causes the current thread to wait until the thread that called the join() method finishes before resuming execution. When WE talked about the happens-before visibility model, what it does is it makes the results of the execution of a thread visible to subsequent threads, right?

// The synchronization code block obtains the object lock of the thread object
// If called from the main thread, the main thread acquires the lock on t
public final synchronized void join(long millis)
    throws InterruptedException {
        long base = System.currentTimeMillis();
        long now = 0;

        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (millis == 0) {
            while (isAlive()) {
            // The main thread will block and enter a blocking state.
            // When the current thread T1 completes, the JVM calls notifyAll of the current thread T1 to wake up the main thread.
                wait(0); }}else {
            while (isAlive()) {
                long delay = millis - now;
                if (delay <= 0) {
                    break; } wait(delay); now = System.currentTimeMillis() - base; }}}Copy the code
What if you want multiple threads to execute sequentially? You can use the Join method.

Join the current thread waits for t1 to complete

Principle:

Join () is a synchronized method that calls wait(). The purpose of this procedure is to make the thread holding the lock wait. Who holds the lock? The main thread is waiting () because the main thread called t1.join(), which is equivalent to writing a block of synchronized code in the t1.join() code block. Then, after the child thread T1 completes execution, the JVM calls Lock. notify_all(Thread); Waking the thread that holds the object lock, the main thread, continues execution.

2, through the ExecutorService. NewSingleThreadExecutor ();

In submitting multiple tasks separately, using a thread pool that creates a single thread, he puts the submitted thread tasks into a FIFO queue and executes them one by one.

Yield method

The thread.yield () method in Java threads translates to Thread yield. As the name implies, when a thread uses this method, it will give up its CPU time and let itself or another thread run, not just another thread. Yield () is used to yield. It can make the current thread from “running state” into “ready state”, so that other waiting threads with the same priority to obtain the execution right; However, there is no guarantee that after the current thread calls yield(), other threads with the same priority will get the right to execute; It is also possible that the current thread enters the “running state” again and continues running!

What is thread safety

atomic

visibility

order

What is a thread deadlock

Deadlock:

A group of threads competing for resources causes “permanent” blocking because they wait for each other.

Lock:

A live lock is a process in which a task or performer is not blocked, but is repeatedly tried-fail-tried-failed because some condition is not met. An entity in a live lock is in a state of constant change, and the live lock may unlock itself

Conditions under which a deadlock occurs

1. A deadlock occurs when all four conditions are met.

Mutually exclusive. Shared resources X and Y can only be occupied by one thread.

Hold and wait. Thread T1 has acquired shared resource X and does not release shared resource X while waiting for shared resource Y.

Non-preemption. Other threads cannot forcibly preempt resources occupied by thread T1.

A circular wait, in which thread T1 waits for resources held by thread T2, and thread T2 waits for resources held by thread T1, is called a circular wait.

2, how to solve the deadlock problem according to the above mentioned four deadlock conditions, we only need to break one of the deadlock, can avoid the occurrence of deadlock.

We can't break the mutual exclusion condition, because that's what we use locks for, but we can break the other three conditions. We can apply for all resources at once, so there's no waiting. As for the condition of "non-preemption", the thread that occupies part of the resource can actively release the occupied resource when applying for other resources. In this way, the condition of "non-preemption" is broken. The "circular waiting" condition can be prevented by applying resources sequentially. The so-called sequential application means that resources are in linear order. When applying, you can apply for resources with small serial number first and then apply for resources with large serial number. In this way, there will be no cycle after linearization.Copy the code