Java thread notes

A thread does not own system resources. A thread has its own stack, counters, etc., but it is a resource shared with other threads of the process, not its own.
Threads run independently. It is not known whether there are other threads, but they can communicate programmatically through sharing. The scheduling method is priority + preemption.
Because the process does not need to allocate independent process space, it is more efficient.
Application instance of process:
1. word input and check on input
2. The browser downloads multiple pictures at the same time
3. Play and display while changing Download

Status of the process:
newBorn: it is created but not started. It can be started through the start method to generate the system resources required by this process. Enter the Runnable state by calling the run method
Runnable state: the thread is in the ready state and waits for processor resources in the queue according to priority and first come first served
Running status: running. Exit the running status after the execution of the run method is completed. Unless the process is actively abandoned or preempted by a higher priority process, it will run all the time.
Blocked state: blocked. The process cannot enter the ready queue in this state and needs to be awakened at another time Beware of possible deadlock entry
Dead status: execution completed or forcibly interrupted. Dead is dead. You can't run it again through the start method. The stop method class is forced to stop, but it has not been recommended.


Conditions and methods for process exiting from running
1. Active release or preemption by higher priority
2. Sleep method and yield method. Yield only gives execution opportunities with the same priority. Note: after the sleep, the runnable status is entered, not running
3. Wait wait for the method of the required variable
4. Input / output thread blocking
5. The suspend method is no longer recommended

/**
 * How to use inheritance threads
 * 1,Write a class to inherit the Thread class, and then you must override the run method
 * 2,Create a new object in the main thread, and then use the run method
 */
class CreatThread extends Thread { // Thread belongs to lang package and does not need to be introduced separately

    // The run method must be written to override the parent class
    public void run() {
        System.out.println();
        System.out.println("Child thread start:" + this);
        System.out.println(this.getName()); //The getName method gets the thread name
        for (int i = 0; i < 4; i++) {
            System.out.println(this + "." + i);
        }
    }
}

public class ThreadTest {
    public static void main(String[] args) {
        CreatThread thread1 = new CreatThread();
        CreatThread thread2 = new CreatThread();
        thread1.start();
        thread2.start();
        /**
         * Sub thread start: Thread[Thread-1,5,main]
         * Sub thread start: Thread[Thread-0,5,main]
         * Thread-0
         * Thread[Thread-0,5,main].0
         * Thread-1
         * Thread[Thread-0,5,main].1
         * Thread[Thread-1,5,main].0
         * Thread[Thread-0,5,main].2
         * Thread[Thread-0,5,main].3
         * Thread[Thread-1,5,main].1
         * Thread[Thread-1,5,main].2
         * Thread[Thread-1,5,main].3
         */
    }
}

Note: thread Currentthread is a static method that returns the currently executing process (the main process)
The getPriority and setPriority methods get and set the priority

Since the stop method is no longer recommended, how to stop the process?

//It's annoying to think about the class name every time you use it once, so you need anonymous classes
class X extends Thread{
private boolean running=false;
public void run(){
while(running){
do something
}
}

public void start(){
running=true;
super.start;
}

public void halt(){
running=false;
}

Because 1. When creating threads in inheritance mode, multiple threads cannot share instance variables directly! 2. java can only inherit, and some classes such as Frame or Applet must be extended
Therefore, the runnable interface is required to create the process

The Runnable interface implements threads

public class ThreadTestByImplements implements Runnable{
    /**
     * implements Method of realizing process
     * 1,Inherit Runnable interface
     * 2,The run method must be overridden
     * 3,In the constructor or method, Thread name = new Thread(this) becomes a thread, and then name The run method is called automatically by start()
     * Note: new Thread(this, "name") can specify a name for the thread
     * 4,Since it is best to set the stop mechanism, you can use the following template when writing code.
     */
    private Thread threadName=null;
    public void start(){
        if(threadName==null){
            threadName=new Thread(this);
            threadName.start();
        }
    }

    public void stop(){
        threadName=null;
    }

    public run(){
        //You can obtain the process name through currentThread, and then judge whether the names are equal
        //do concrete logic
    }


    public static void main(String[] args) {
        ThreadTestByImplements a = new ThreadTestByImplements();
        a.start();
        a.run();
        a.stop();
    }


}

Example: output the time every second. Since this example cannot block other operations, it is best to use the process to write

import java.util.Date;

public class ThreadTestByImplements implements Runnable{
    private Thread clocker = null;
    //Open thread in constructor
    public ThreadTestByImplements(){
        clocker = new Thread(this);
        clocker.start(); //The need to write the start method manually is different from inheritance
    }
    //The run method is required, and the specific logic is written here
    public void run(){
        while(true){
            Date now = new Date();
            System.out.println(now);
            try{
                clocker.sleep(1000);//You can also directly thread Sleep is to make the currently running process sleep, which is actually a clocker
            }catch(InterruptedException e){

            }
        }

    }

    public static void main(String[] args) {
        ThreadTestByImplements aBC = new ThreadTestByImplements();
    }



}

The process created by Callable method is not well written. I won't look at it for the time being

Daemon Thread -- background process and daemon

JVM garbage collection is a typical background thread
Feature: if all foreground processes die, the background process will also die
Designated by setDaemon(true) as a background process (must be called before start method).

Thread safety - thread synchronization

Problem introduction: for example, when two people deposit and withdraw from an account at the same time, when the thread just reads the balance and is ready to deduct money, or determines whether the balance is sufficient, the process switches. Then it will lead to wrong results

Method 1

To do this, use synchronized to lock the thread
Use method 1: the method is declared as synchronized
Use method 2: synchronized (parameter variable to lock) {code block}

Tube (mutually exclusive lock), lock (synchronous lock)

Thread communication

1. When Syn is used, the wait method waits for other threads to notify() or notifyAll() before continuing
2. When using Lock, you can't use the above method, but use Condition control
3. Blocking queue introduced by Java 5

Thread group

The constructor implementation using Tread is not described here

Thread pool

The cost of starting a new thread is relatively high because it is designed to interact with the operating system. When many threads with a very short lifetime are required, the thread pool can be used to innovate a large number of empty threads in advance.

Keywords: Java Back-end

Added by mark_c on Sun, 16 Jan 2022 19:08:59 +0200