The difference between threads and processes

A process is an independent runtime environment, and a thread is a task executed in a process

Their essential difference is: whether to separate memory address space and other system resources

The process is the basic unit of resource allocation by the operating system, and the thread is the basic unit of scheduling by the operating system, that is, the unit of CPU allocation time

Implementation of threads

In Java, the JDK provides the Thread class and the Runnable interface to allow us to implement our own threading classes

  • Inherit from Thread and override the run method
  • Implement the run method of the Runnable interface
Thread class inheritance
public class Demo {
    public static class MyThread extends Thread {
        @Override
        public void run(a) {
            System.out.println("MyThread"); }}public static void main(String[] args) {
        Thread myThread = newMyThread(); myThread.start(); }}Copy the code

After we call the start() method in our program, the virtual machine creates a thread for us and then calls the run() method when the thread gets its first slice of time

Note: start () method cannot repeat calls, repeated calls to sell Java lang. An IllegalStateException anomalies

Implement the Runnable interface
public class Demo {
    public static class MyThread implements Runnable {
        @Override
        public void run(a) {
            System.out.println("MyThread"); }}public static void main(String[] args) {

        new Thread(new MyThread()).start();

        // Java 8 functional programming, you can omit the MyThread class
        new Thread(() -> {
            System.out.println("Java 8 Anonymous Inner Classes"); }).start(); }}Copy the code

Several common methods of the Thread class

  • CurrentThread () : Static method that returns a reference to the thread object currently executing
  • Start () : The method that starts the execution of the thread. The Java virtual machine calls the run() method within the thread
  • Yield () : The current thread is willing to yield its usage of the current processor. In this case, even if the current thread calls the yield() method, it is still possible for the program to continue running the thread when it is scheduled
  • Sleep () : a static method that makes the current thread sleep for a certain period of time
  • Join () : causes the current thread to wait for another thread to finish executing before continuing. The internal call is implemented by the Object class wait method

The interview questions

What are the states of the thread and how does it work

The Thread states are defined as enumerations in the Thread source code. There are six states:

/ / Thread. State the source code
public enum State {
    NEW,
    RUNNABLE,
    BLOCKED,
    WAITING,
    TIMED_WAITING,
    TERMINATED;
}
Copy the code
  • NEW: NEW is not started, the thread is created without the start() method being called, and the thread is in the NEW state

  • RUNNABLE: Indicates that the current thread is running. Threads in the RUNNABLE state are running in the Java virtual machine and may be waiting for the CPU to allocate resources

  • The state of a thread waiting for a lock indicates that the thread in the BLOCKED state is waiting for a monitor lock, such as a method that executes a synchronized block of code or uses synchronized tags

  • A thread in the wait state is WAITING for another thread to perform a particular action, wake up: object.notify () or object.notifyAll ()

    Calling the following three methods puts the thread into a wait state:

    • Object.wait() : causes the current thread to wait until another thread wakes it up;
    • Thread.join() : wait for the Thread to finish executing.
    • Locksupport.park () : Disables the current thread for thread scheduling unless authorized to call
  • TIMED_WAITING, the WAITING state, is similar to WAITING, except that it has an extra timeout, Wait (Long Timeout) and Thread.join(Long Timeout), for example, will enter this state

  • TERMINATED state, indicating that the thread has completed execution

** Thread working mode: ** Create a thread and specify the business method it needs to execute. Then call the thread’s start() method, which changes the thread from a NEW state to a RUNNABLE state. If the lock exists and is being used by other threads, the thread becomes BLOCKED, and when the lock is used by other threads, the thread continues to execute the remaining methods

WAITING () or thread.join (), or TIMED_WAITING (with a timeout). After another thread has executed the notify() or notifyAll() method, the thread is awakened to continue executing the remaining business methods until the method execution is complete

BLOCKED and WAITING

BLOCKED means that a thread is still active and is blocking until other threads have used up a lock resource

WAITING is itself called object.wait (), thread.join (), or lockSupport.park (), and it can only wake you with a specific action on it

The difference between Start() and run()

Start () the source code

public synchronized void start(a) {
    // If the state is not equal to NEW, an exception will be thrown
    if(threadStatus ! =0)
        throw new IllegalThreadStateException();
    // Notifies the thread group that the thread is about to start

    group.add(this);
    boolean started = false;
    try {
        start0();
        started = true;
    } finally {
        try {
            if(! started) { group.threadStartFailed(this); }}catch (Throwable ignore) {
            // No exceptions are handled. If start0 throws an exception, it is passed on to the call stack}}}Copy the code

The run () the source code

@FunctionalInterface
public interface Runnable {
    public abstract void run(a);
}
Copy the code

The start() method is Thread’s own method, and synchronized is used to ensure thread-safety

The run() method is an abstract method of Runnable and must be overridden by the calling class. The overridden run() method is actually the business method that the thread is going to execute

In terms of execution effects, the start() method turns on multiple threads, making them transition from a NEW state to a RUNNABLE state, while the run() method is just a normal method.

Start () method cannot be called multiple times, otherwise will be thrown. Java lang. An IllegalStateException; The run() method, on the other hand, can be called multiple times because it’s just a normal method

What is the use of thread priorities

// The lowest priority a thread can have
public final static int MIN_PRIORITY = 1;

// Thread default priority
public final static int NORM_PRIORITY = 5;

// The maximum priority that a thread can have
public final static int MAX_PRIORITY = 10
Copy the code

The priority of a thread is preemptive, that is, the probability of a thread preempting a slice of CPU time. The higher the priority, the higher the probability of a thread preempting a slice of CPU time

Thread.setpriority (int newPriority) is used to set the priority