33. Custom thread

1. Process

Definition: An ongoing program is called a process. The process is responsible for the division of memory space

Question: Windows claims to be a multitasking operating system, so does it run multiple programs at the same time?

  From a macro point of view: windows is indeed running multiple applications at the same time

  From a microscopic point of view: the cpu does a fast switching action, but it is too fast, and we cannot see the switching with the naked eye.

 

2. Thread

Definition: A thread is responsible for the execution of code in a process, which is the path of a process

 

3. Multithreading

Definition: There are multiple threads executing different code in a process.

 

Question: According to the above definition, why can our previous program be executed?

   It turns out that when we run the program, the jvm will create a main thread to execute the code in the main method

Note: There are at least 2 threads in a java, one is the mian thread, and the other executes the garbage collector

The benefits of multithreading:

      1. Solved the problem of one process performing multiple tasks

      2. Increased resource utilization (rather than increased efficiency)

Disadvantages of multithreading:

      1. Increase the burden on the cpu

      2. Reduced the execution rate of a thread

      3. Raised thread safety questions

      4. There is a deadlock phenomenon

 

4. Create a thread

method one:

    1. Customize a class to inherit the Thread class

    2. Rewrite the run method

      Question: Why do we need to override the run method of the parent class? (The run method is the code to be executed by the thread)

        It turns out that each thread has its own task code. For example, the main thread executes the code in the main method.

        And the thread we define, of course, has to execute its own task code, so we write the task code in the run method

    3. Create a subclass object of the Thread thread and call the start method

      Question: Why do we need to call the start method to start a custom thread? I did not define the start method?

        It turns out that when we use the child object to call the start method, we actually call the start method of the Thread class, and let the start method call the run method.

    注意:不要直接调用run方法,如果直接调用run方法,那么就相当于调用了一个普通的方法,并没开启线程

 

下面是一个线程的Demo,可以看出来cpu是在主线程和自定义线程中切换执行的。

class sonThread extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("我是自定义线程");
        }
    }
}

public class Demo3 {
    public static void main(String[] args) {
        
        sonThread sonthread = new sonThread();
        sonthread.start();
        for (int i = 0; i < 100; i++) {
            System.out.println("我是main线程");
        }
    }
}

 

 

5.线程的生命周期

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325016463&siteId=291194637