Multithreading (Thread)

Multithreading (Thread)

1. Know threads

concept:

  • Process is the smallest unit of system allocation of resources , thread is the smallest unit of system scheduling . Resources can be shared between threads in a process. At least one thread exists in each process, that is, the main thread .

2. Feel the thread with code

public class ThreadDemo {
    
    
    /**
     * 内部实现静态线程类
     */
    private static class MyThread extends Thread{
    
    
        //1.重写run方法

        @Override
        public void run() {
    
    
            System.out.println("第一个线程代码感受!");
        }
    }

    public static void main(String[] args) {
    
    
        MyThread myThread = new MyThread();
        myThread.start();
    }
}
import java.util.Random;

public class ThreadDemo {
    
    
    /**
     * 内部实现静态线程类
     */
    private static class MyThread extends Thread{
    
    
        //1.重写run方法

        @Override
        public void run() {
    
    
            //System.out.println("第一个线程代码感受!");
            Random random = new Random();
            while (true) {
    
    
                // 打印线程名称
                System.out.println(Thread.currentThread().getName());
                try {
    
    
                    // 随机停止运行 0-9 秒
                    Thread.sleep(random.nextInt(10));
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
    
    
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();
        MyThread t3 = new MyThread();
        t1.start();
        t2.start();
        t3.start();


        Random random = new Random();
        while (true){
    
    
            //currentThread()返回对当前正在执行的线程对象的引用
            System.out.println(Thread.currentThread().getName());
            try {
    
    
                Thread.sleep(random.nextInt(10));
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }
    }
}

result:
Insert picture description here

3. There are two ways to create a new thread of execution

  • There are two ways to create a new thread of execution. One is to declare a class as a subclass of Thread. This subclass should override the Thread method of the run class . Then you can allocate and start instances of the subclass. (That is the feeling code above).
  • Another way to create a thread is to declare the implementation of the Runnable interface . That class then implements the run method. Then you can allocate an instance of the class, pass it as a parameter when creating a Thread, and start it. (as follows).

start() causes this thread to start execution; the Java virtual machine calls the run method of this thread .

public class ThreadDemo {
    
    
   
    private static class MyThread2 implements Runnable{
    
    
        @Override
        public void run() {
    
    
            System.out.println("继承Runable实现线程");
        }
    }

    public static void main(String[] args) {
    
    
        MyThread2 myThread2 = new MyThread2();
        new Thread(myThread2).start();
    }
}

4. The advantage of multi-threading-increase the running speed

  • Next, through the operation of the code, feel whether multi-threading has increased the running speed ;
  • It can be observed that multithreading can improve the overall operating efficiency of the program in some situations ;
package 通过代码感受线程;

/**
 * 多线程的优势-增加运行速度
 */
public class ThreadDemo2 {
    
    
    private static final long count = 10_0000_0000;

    public static void main(String[] args) throws InterruptedException {
    
    
        //1.使用并发的方式,也就是多线程的方法
        concurrency();

        //2.使用串行的方式,也就是我们正常写代码的方式,对比多线程来说就是单线程,全部靠主线程来进行运算
        serial();
    }

    //多线程
    private static void concurrency() throws InterruptedException {
    
    
        long begin = System.currentTimeMillis();//开始运行时间
        //1.利用子线程计算a的值
        Thread thread = new Thread( new Runnable(){
    
    
            @Override
            public void run() {
    
    
                long a = 0;
                for (long i = 0;i < count;i++){
    
    
                    a++;
                }
            }
        });
        thread.start();
        //2.主线程计算b的值
        long b =0;
        for (long i = 0;i < count;i++){
    
    
            b++;
        }
        // 等待 thread 线程运行结束
        thread.join();

        long end = System.currentTimeMillis();//运行结束时间

        System.out.println("多线程时间是:"+(end-begin));
    }

    //单线程
    private static void serial() {
    
    
        long begin = System.currentTimeMillis();//开始运行时间
        //1.将a和b的计算全部都放在主线程里面
        long a = 0;
        for (long i = 0;i < count;i++){
    
    
            a++;
        }

        long b = 0;
        for (long i = 0;i < count;i++){
    
    
            b++;
        }

        long end = System.currentTimeMillis();//运行结束时间

        System.out.println("单线程时间是:"+(end-begin));
    }
}

result:
Insert picture description here

5. Thread class and common methods

6. Observe all the status of the thread

public class ThreadDemo {
    
    
    /**
     * 观察线程的所有状态,总共有6中状态
     * NEW :新建
     * RUNNABLE :就绪
     * BLOCKED : 阻塞
     * WAITING:等待
     * TIMED_WAITING :带时限的等待(超时等待)
     * TERMINATED : 终止
     * @param args
     */
    public static void main(String[] args) {
    
    
        for (Thread.State state : Thread.State.values()){
    
    
            System.out.println(state);
        }
    }
}

The results show that:
Insert picture description here

1. The life cycle of threads in Java

Insert picture description here

Insert picture description here

7. Multi-threaded case series-singleton model (hungry man mode and lazy man mode)

Guess you like

Origin blog.csdn.net/qq_45665172/article/details/113809014