Basic concepts of thread

What is a process? What is a thread

Process: simple explanation, an application on the computer hard disk, such as QQ Exe, when it runs, is called a process.

Thread: the smallest execution unit in a process is called a thread.

Several ways of creating process

1. Inherit the Thread class and override the run() method

2. Implement the Runnable interface and rewrite the run() method

3. Implement the Callable interface and call() method again

4. Create thread pool

public class Test1 {
    public static void main(String[] args) {
        // Inherit the Thread class and rerun () method
        new MyThread().start();
        // Implement the Runnable interface and rewrite the run() method
        new Thread(new MyRun()).start();
        // Implement the Callable interface and call() method again
        new Thread(new FutureTask<>(new MyCall())).start();
        // Thread pool create thread
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(() -> {
            System.out.println("ThreadPool Create thread");
        });
    }

    public static class MyThread extends Thread {
        @Override
        public void run() {
            System.out.println("inherit Thread Class method");
        }
    }

    public static class MyRun implements Runnable {
        @Override
        public void run() {
            System.out.println("realization Runnable Interface method");
        }
    }

    public static class MyCall implements Callable<String> {
        @Override
        public String call() throws Exception {
            System.out.println("realization Callable Interface method");
            return "success";
        }
    }
}

Thread method

1. sleep method

sleep Sleep: the current thread pauses for a period of time to allow other threads to run. When the sleep time is up, it will be revived automatically
public class Test2 {

    public static void main(String[] args) {
        testSleep();
        for (int j=0;j<100;j++){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("main"+j);
        }
    }

    public static void testSleep(){
        new Thread(()->{
            for (int i=0;i<100;i++){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("thread"+i);
            }
        }).start();
    }
}

2. yield method

​ The yield method means that when the current thread is executing, it stops to enter the waiting queue and returns to the waiting queue. In the scheduling algorithm of the system, it is still possible to take this thread back and continue to execute. The greater possibility is to take out an execution of the original waiting thread. So yield means that I give up the CPU and whether you can grab it later.

public class Test3 {
    public static void main(String[] args) {
        testYield();
    }

    public static void testYield() {
        new Thread(() -> {
            for (int i=0;i<100;i++){
                System.out.println("A" + i);
                if (i%10 ==0){
                    Thread.yield();
                }
            }
        }).start();
        new Thread(() -> {
            for (int i=0;i<100;i++){
                System.out.println("B" + i);
                if (i%10 ==0){
                    Thread.yield();
                }
            }
        }).start();
    }
}

3. join method

​ The join method is to add the thread calling join() to its current thread. This thread waits until the calling thread runs, and then runs it by itself. t1 and t2 threads call t2 at a certain time point of t1 It will run at t1, and it will run at t2

public class Test4 {
    public static void main(String[] args) {
        testJoin();
    }

    public static void testJoin() {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("A" + i);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread t2 = new Thread(() -> {
            try {
                t1.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < 5; i++) {
                System.out.println("B" + i);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        t2.start();
    }
}

Operation results:

[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-vp0cyln7-1596356028254) (C: \ users \ combi \ appdata \ roaming \ typora user images \ 1596354297992. PNG)]

Thread state

[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-voiqj4je-1596356028258) (C: \ users \ combi \ appdata \ roaming \ typora \ typora user images \ 15963547356. PNG)]

There are six common states of threads:

1. NEW status (NEW)

use**new keyword**Create a new thread, which is in**New status**.  

2. Running status (RUNNABLE)

​ The ready and running states in the operating system are collectively referred to as RUNNABLE in Java.

Ready status (READY)

When a thread object calls start()Method, the thread is in**Ready status**,Ready means that the thread**Can execute**,But when it will be implemented will depend on JVM Scheduling in thread scheduler. 
  • It is not allowed to use start multiple times on a thread.

  • After the thread has finished executing, you cannot attempt to wake it up with start.

Other status - > ready

  • The thread calls start(), and the new state is converted to ready state.
  • When the thread sleep(long) time expires, the waiting state changes to ready state.
  • The result of blocking IO operation returns and the thread becomes ready.
  • Other threads call the join() method and convert to the ready state after completion.
  • After the thread object gets the object lock, it will also enter the ready state.

Running status

​ After the thread in the ready state obtains the CPU, when it really starts executing the thread execution body of the run() method, it means that the thread is already in the running state. It should be noted that * * for a single processor, only one thread can be running at a time** For the preemptive system, the system will give each thread a short period of time to process its own tasks. After the time runs out, the system is responsible for recapturing the resources occupied by the thread. In the next period of time, the system will schedule again according to certain rules.

Operation status - > ready status:

  • The thread lost processor resources. The thread may not execute completely. If it is half executed, it may be robbed by other threads.

  • Call the yield() static method, temporarily suspend the current thread, and let the thread scheduler of the system reschedule once. It is entirely possible for it to run again.

    Prompt the scheduler that the current thread is willing to give up the current use of the processor. At this time, the current thread will be set to the ready state and wait for scheduling like other threads. At this time, according to the probability determined by different priorities, the current thread is completely possible to grab processor resources again.

3. Blocked

A blocked state indicates a state in which a thread is waiting for a monitor lock.

The following scenario threads will block:

  • The thread waits to enter the synchronized synchronization method.
  • The thread waits to enter the synchronized code block. When a thread acquires a lock, it changes from a blocked state to a ready state.

4. Waiting status

​ Entering this state indicates that the current thread needs to wait for other threads to make some specific actions (notifications or interrupts).

Run - > wait

  • When the current thread is running, other threads call the join method, and the current thread will enter the waiting state.
  • The current thread object calls the wait() method.
  • LockSupport.park(): disables the current thread for thread scheduling purposes.

Wait - > ready

  • The waiting thread is awakened by other thread objects, notify() and notifyAll().

  • LockSupport.unpark(Thread), corresponding to the above park method, gives the license and releases the waiting state.

5. Timed_waiting

​ Different from WAITING, it can return by itself at a specified time.

Run - > timeout wait

  • Call static method, thread sleep(long)

  • The thread object calls the wait(long) method

  • Other threads call join(long) at the specified time

  • LockSupport.parkNanos()

  • LockSupport.parkUntil().

  • Supplement: the difference between sleep and yield:

    The sleep(long) method will make the thread enter the timeout waiting state, and it will not enter the ready state until the time is up. The yield() method does not turn the thread into a wait, but forces the thread into a ready state. Using the sleep(long) method requires handling exceptions, while yield() does not.

Timeout - > ready

  • Similarly, the waiting thread is awakened by other thread objects, notify() and notifyAll().

  • LockSupport.unpark(Thread).

6. Extinction state

That is, the termination of the thread indicates that the thread has been executed. As mentioned earlier, dead threads cannot be awakened again through start.

  • The run() and call() threads are successfully executed in the execution body, and the thread terminates normally.

  • The thread throws an Exception or Error that is not captured.

The long () method needs to handle exceptions, but yield() doesn't.

Timeout - > ready

  • Similarly, the waiting thread is awakened by other thread objects, notify() and notifyAll().

  • LockSupport.unpark(Thread).

6. Extinction state

That is, the termination of the thread indicates that the thread has been executed. As mentioned earlier, dead threads cannot be awakened again through start.

  • The run() and call() threads are successfully executed in the execution body, and the thread terminates normally.

  • The thread throws an Exception or Error that is not captured.

    It should be noted that the main thread and the sub thread do not affect each other, and the sub thread will not end because the main thread ends.

Tags: Java Multithreading

Posted by lill77 on Wed, 25 May 2022 15:54:58 +0300