Java multi-threading basics & 4 ways to create threads

what is process

进程就是系统中正在运行的一个程序,程序一旦运行就是一个进程,在一个进程中可以开启多个不同的线程执行。

What is multithreading

多线程就是同一进程下开启多条执行路径,同时执行,互不影响

Benefits of using multithreading

1、提高程序执行效率
2、快速响应给客户端,给用户较好的体验
3、每个线程之间相互不影响

Application scenarios using multi-threading

1.使用多线程实现异步发送短信
2.使用多线程实现异步的记录日志
3.使用多线程处理一些比较耗时间的业务逻辑

Difference Between Single Threading and Multithreading

单线程:串行执行代码,效率不高,且响应较慢,对用户不是太友好
多线程:进程开启多条线路执行代码,每条线程执行不同的任务,每个线程之间相互不影响

How to understand thread context switching

对于单核的CPU来说,CPU在同一个时刻只能够运行一个线程,当正在运行的线程切换到另外一个线程时,这个过程我们可以理解为CPU上下文切换。
如果是多核处理器,比如 6核 12线程,也就是在同一个时刻可以开启12个线程同时运行,服务器支持的线程数越高可以减少CPU上下文的切换,从而提高效率。
所以注意:单核的服务器开启了多线程,人为感知好像是多线程,但是真正意义上的底层不是多线程。

Is it true that the more multi-threading is enabled, the better?

如果项目比较小的情况下可以采用多线程异步实现处理是可以的,但是如果在高并发的情况下频繁的创建线程,同时也会被CPU分配调度,不断的切换,对服务器影响也是比较大,所以建议如果是在高并发的情况下采用MQ异步的形式替代多线程。

4 ways to create threads

1. Inherit the Thread class
public class Thread1 extends Thread {
    
    

    @Override
    public void run() {
    
    
        System.out.println("我是子线程:" + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
    
    
        System.out.println("我是主线程:" + Thread.currentThread().getName());
        // 调用start方法启动线程
        new Thread1().start();
    }
}
2. Use Runnable
public class Thread2 implements Runnable {
    
    
    public void run() {
    
    
        System.out.println("我是子线程:" + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
    
    
        System.out.println("我是主线程:" + Thread.currentThread().getName());
        new Thread(new Thread2()).start();
    }
}
3. Use Callable
public class MyCallable implements Callable<String> {
    
    
    public String call() throws Exception {
    
    
        System.out.println(Thread.currentThread().getName() + "正在异步调用接口发送短信");
        try {
    
    
            Thread.sleep(3000);
        } catch (Exception e) {
    
    

        }
        return "短信发送成功";
    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {
    
    
        FutureTask<String> futureTask = new FutureTask<String>(new MyCallable());
        Thread thread = new Thread(futureTask);
        thread.start();
        String result = futureTask.get();
        System.out.println(Thread.currentThread().getName() + result);
    }
}
4.Thread pool method
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(new Runnable() {
    
    
    public void run() {
    
    
        System.out.println(Thread.currentThread().getName());
    }
});

Five states of multithreading

1.当我们新建一个线程的时候,new Thread的时候为新建的状态。
2.当我们调用到start方法的时候,不会立马执行到我们的run方法,当前线程状态为就绪状态,需要等待cpu的切换。
3.当cpu切换能够调用到该线程的时候,当前线程的状态
为运行状态。
4.当我们在线程调用sleep方法的时候,当前线程线程的状态为
阻塞状态,当休眠的时候过了的时候有需要从新等待cpu调度,从就绪状态到运行。
5.当我们线程调用stop方法或者run方法代码执行结束的时候
当前线程的状态为死亡状态。

Insert image description here

How to gracefully stop a thread

Officials do not recommend calling the stop method directly to stop the thread. It is recommended to use the middleware variable value to stop the thread. You can also use a daemon thread.

public class Thread005 extends Thread {
    
    
    private volatile boolean flag = true;
    @Override
    public void run() {
    
        System.out.println(Thread.currentThread().getName());
        while (flag) {
    
    
        }
    }
    public void stopThread() {
    
    
        this.flag = false;
    }
    public static void main(String[] args) {
    
    
        Thread005 thread005 = new Thread005();
        thread005.start();
        try {
    
    
            Thread.sleep(3000);
            thread005.stopThread();
        } catch (Exception e) {
    
    
        }
    }
}

Guess you like

Origin blog.csdn.net/weixin_44606481/article/details/108865433