Introduction to JAVA threads


What is a program?

It is a set of instructions written in a certain language to complete a specific task. `
Simply put: it is the code we write


What is a process?

A process refers to a running program. The operating system will allocate memory space for the process. A process
is an execution process of your program, or a program that is running. It is a dynamic process. Its own generation, existence and death process

启动一个程序
insert image description here
启动两个程序
insert image description here
After the process is terminated, the process will die


What are threads?

1. A thread is created by a process and is the entity of a process 2. A process can have
multiple threads
Every time something is downloaded, a corresponding thread is started

single-threaded vs. multi-threaded

Single-threaded: At the same time, only one thread is allowed to execute
Multi-threaded: At the same time, multiple threads can be executed, such as downloading things from Baidu Netdisk

Concurrency and Parallelism

Concurrency: At the same time, multiple tasks are executed alternately, creating an illusion that you seem to see them at the same time. Simply put, the multi-tasking achieved by a single-core cpu is concurrent and parallel: at the same time, multiple tasks are executed at the same time. Multi-core cpu
can To achieve parallelism
, you can think of cpu as our brain. There is only one for each person. Can you watch TV and do homework all over again? You may feel in your heart that you can have this ability, but in fact you are watching TV and doing homework. Switching back and forth in the process

并发和并行可能同时存在


use of threads

Use java to check how many CPUs there are

Sample code:

public class CpuNum {
    
    
    public static void main(String[] args) {
    
    
        Runtime runtime = Runtime.getRuntime();
        //获取当前电脑的cpu数量
        int cpuNums = runtime.availableProcessors();
        System.out.println("当前有cpu个数 = "+cpuNums);
    }
}

operation result:

insert image description here

Two ways to create threads

Inherit the Thread class and rewrite the run method

Example: Output a kitten meowing every 1s

public class Thread01 {
    
    
    public static void main(String[] args) {
    
    
        //创建Cat对象,可以当线程使用
        Cat cat = new Cat();
        cat.start();//启动线程
    }
}
//1.当一个类继承了Thread类,该类就可以当作线程使用
//2.我们会重写run方法,写上自己的业务代码
//3.run Thread 类 实现了Runnable接口的run方法
/* @Override
public void run() {
if (target != null) {
target.run();
}
}*/
class Cat extends Thread{
    
    
    int times  = 0;
    @Override
    public void run() {
    
    //重写run方法,写上自己的业务逻辑
        while(true) {
    
    
            //该线程每隔1秒,在控制台输出”喵喵,我是小猫咪“
            System.out.println("喵喵,我是小猫咪"+(++times));
            //让该线程休眠1秒
            try {
    
    
                Thread.sleep(1000);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }
    }
}

Example: After the above basis, add a condition that only outputs 8 times

public class Thread01 {
    
    
    public static void main(String[] args) {
    
    
        //创建Cat对象,可以当线程使用
        Cat cat = new Cat();
        cat.start();//启动线程
    }
}
//1.当一个类继承了Thread类,该类就可以当作线程使用
//2.我们会重写run方法,写上自己的业务代码
//3.run Thread 类 实现了Runnable接口的run方法
/* @Override
public void run() {
if (target != null) {
target.run();
}
}*/
class Cat extends Thread{
    
    
    int times  = 0;
    @Override
    public void run() {
    
    //重写run方法,写上自己的业务逻辑
        while(true) {
    
    
            //该线程每隔1秒,在控制台输出”喵喵,我是小猫咪“
            System.out.println("喵喵,我是小猫咪"+(++times));
            //让该线程休眠1秒
            try {
    
    
                Thread.sleep(1000);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
            if(times==8){
    
    
                break;//当times 到80,退出while,这时线程就会结束
            }
        }
    }
}

Implement the Runnable interface and rewrite the run method

Implementation example: Please write a program that can output "hi" on the console every 1 second, and automatically exit after outputting 10 times

public class Thread02 {
    
    
    public static void main(String[] args) {
    
    
        Dog dog = new Dog();
        //dog.start();这里不能调用start
        //创建Thread对象,把dog对象(实现Runnable),放入Thread
        Thread thread = new Thread(dog);
        thread.start();
    }
}
class Dog implements Runnable{
    
    //通过实现Runnable接口,并发线程
    int count = 0;
    @Override
    public void run() {
    
    //普通方法
        while(true){
    
    
            System.out.println("小狗汪汪叫..hi"+(++count)+Thread.currentThread().getName());
            try {
    
    
                Thread.sleep(1000);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
            if(count==10){
    
    
                break;
            }
        }
    }
}

这里底层使用了设计模式(代理模式)
模拟代理类

//线程代理
class ThreadProxy implements Runnable{
    
    //把Proxy当成ThreadProxy

    private Runnable target = null;//属性,类型是Runnable
    @Override
    public void run() {
    
    
        if(target!=null){
    
    
            target.run();
        }
    }

    public ThreadProxy(Runnable target){
    
    
        this.target = target;
    }
    public void start(){
    
    
        start0();//这个方法时真正实现多线程方法
    }
    public void start0(){
    
    
        run();
    }
}

multithreading mechanism

Multiple threads running concurrently

Sample code:



public class Thread01 {
    
    
    public static void main(String[] args) throws InterruptedException {
    
    
        //创建Cat对象,可以当线程使用
        Cat cat = new Cat();
        cat.start();//启动线程
        //说明:当main线程启动了一个子线程 Thread-0,主线程不会阻塞,会继续执行
        //这时,主线程和子线程是交替执行
        System.out.println("主线程继续执行"+Thread.currentThread().getName());//名字main
        for (int i=0;i<10;i++){
    
    
            System.out.println("主线程 i="+i);
            //让主线程休眠
            Thread.sleep(1000);
        }
    }
}
//1.当一个类继承了Thread类,该类就可以当作线程使用
//2.我们会重写run方法,写上自己的业务代码
//3.run Thread 类 实现了Runnable接口的run方法
/* @Override
public void run() {
if (target != null) {
target.run();
}
}*/
class Cat extends Thread{
    
    
    int times  = 0;
    @Override
    public void run() {
    
    //重写run方法,写上自己的业务逻辑
        while(true) {
    
    
            //该线程每隔1秒,在控制台输出”喵喵,我是小猫咪“
            System.out.println("喵喵,我是小猫咪"+(++times)+"线程名 = "+Thread.currentThread().getName());
            //让该线程休眠1秒
            try {
    
    
                Thread.sleep(1000);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
            if(times==80){
    
    
                break;//当times 到80,退出while,这时线程就会结束
            }
        }
    }
}

insert image description here
Execution process, when we go to run, we open a process, which starts a main thread for us, and a sub-thread is opened in the main thread, and the process ends when all threads hang up. As long as one thread is alive, the application is not terminated

Why is it start?

run方法就是一个普通的方法,没有真正的启动一个线程,就会把run方法执行完毕才向下执行,即会阻塞
insert image description here

Source code analysis

(1)

public synchronized void start(){
    
    
	start0();
}

(2)
//start0() is a local method, called by jvm, and the bottom layer is c/c++
//The real multi-threading effect is start0(), not run
private native void start0();
start() method call After the start0() method, the thread does not necessarily execute immediately, but just turns the thread into a runnable state. The specific execution time depends on the CPU, which is uniformly scheduled by the CPU.

Guess you like

Origin blog.csdn.net/m0_62434717/article/details/129169810