The basic concept of threads-four basic ways to achieve multithreading

Thread overview

Using multithreading technology can make the system run multiple program blocks at the same time, shorten the response time of the program, improve the utilization rate of computer resources, and achieve the purpose of multitasking.

Processes and threads

  • A process is a dynamic execution process of a program, and each process has its own independent memory space. An application can start multiple processes at the same time (for example, a browser can open multiple windows, and each window is a process)

  • A multi-process operating system can run multiple processes, and each process can recycle the required CPU time slice , making all processes look like they are running at the same time .

  • A thread is an execution flow of a process. A process can be composed of multiple threads, that is, a process can run multiple different threads at the same time , and each thread completes a different task.

  • Concurrent running of threads : that is, several threads running simultaneously in a process. (For example: Word's spell check function and first letter automatic capitalization function are threads in the word process)

  • The relationship between threads and processes is a partial and overall relationship. Each process is allocated an independent memory address space by the operating system, and all threads of the same process work in the same address space.
    Insert picture description here

Thread life cycle

The complete life cycle of a thread has to go through 5 states: new, ready, running, blocked, and dead
Insert picture description here
Insert picture description here

  • New state: Use new and a certain thread construction method to create a thread object, the thread will enter the new state, and the system allocates memory space for the thread object. A thread in the newly created state can enter the ready state by calling the **start()** method.
  • Ready state: At this time, the thread has the conditions to run, enters the thread queue, and waits for the system to allocate CPU resources. Once the CPU resources are obtained, the thread will enter the running state.
  • Running state: When entering the running state, the thread will execute the code in its own **run()** method.
  • Blocking state: If a thread is executing suspend, join or sleep method , or waiting for the right to use the io device, then the thread will give up its CUP control and temporarily suspend its execution, and enter the blocking state. A blocked thread cannot enter the ready queue. Only when the cause of the blocking is eliminated, the thread can enter the ready state, re-enter the thread queue and wait for CPU resources, and then continue execution.
  • Dead state: A thread is in a dead state when it completes all work or is forcibly terminated in advance.

Induction of common thread methods

Method name description
Thread(Runnable target) Use Runnable interface subclass object to instantiate Thread object
Thread(Runnable target,String name) Use the Runnable interface subclass to instantiate the Tread object and specify the thread name
Thread(String name) Instantiate the Thread object, specify the thread name
Thread currentThread() Returns the currently executing thread
String getName() Return thread name
int getPriority() Return thread priority
boolean isInterrupter() Judge whether the thread is interrupted, the thread interruption returns true, otherwise it returns false
boolean isAlive() Judge whether the thread is active, return true, otherwise return false
final void join() Force threads to run (some tasks need to be run urgently)
void run() Execute thread, the main tasks of thread execution are written inside
void sleep() Make the executing thread temporarily sleep (unit / millisecond), and other threads continue to execute
interrupt() Force the terminal thread to run, the method behind the thread will not continue to execute
void yield() Suspend the currently executing thread, and run other threads to execute (let other threads execute, and then resume the thread)
setName() Set thread name
setPriority(int new) Set thread priority, MIN_PRIORITY (constant value 1) lowest priority, NORM_PRIORITY (value 5) medium priority ( thread default priority ), MAX_PRIORITY (value 10) highest priority
void start() Start the thread, enter the ready queue, and wait for the cpu resource to enter the running state
finalv void setDaemon(boolean on) Set a thread to run in the background

Multi-threaded realization method

Case

1. Inherit the Thread class and rewrite the run method to achieve multithreading

public class MyThread extends Thread{
    
    

    private String name;//线程名

    public MyThread() {
    
    
    }
    public MyThread(String name) {
    
    
        this.name = name;
    }
    
    //完成线程功能的主体代码都在run()方法中
    @Override
    public void run() {
    
    
        for (int i = 0; i < 3; i++){
    
    
            System.out.println(name + "执行功能" + i);
        }
    }
}
public class ThreadDemo {
    
    
    public static void main(String[] args) {
    
    
        //定义线程
        MyThread thread1 = new MyThread("线程A");
        MyThread thread2 = new MyThread("线程B");
        MyThread thread3 = new MyThread("线程C");
        MyThread thread4 = new MyThread("线程D");
        MyThread thread5 = new MyThread("线程E");
        MyThread thread6 = new MyThread("线程F");

        //调用start()方法启动线程,让其进入就绪状态,等待系统分配CPU资源进入运行状态调用run()方法
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        thread5.start();
        thread6.start();
    }
}

Running results: (based on a 4-core computer)
running three threads (sequential execution)
Insert picture description here
running 6 threads (interactive execution)
Insert picture description here

2. Inherit the Runnable interface to achieve multithreading

  Override the run method to implement the instance object of the implementation class of the Runnable interface as the target of the Thread constructor

class MyRunnable implements Runnable {
    
    

    @Override
    public void run() {
    
    
        for(int i = 0; i < 3; i++){
    
    
            System.out.println(Thread.currentThread().getName()+"运行功能"+i);
        }
    }
}

public class RunnableDemo {
    
    
    public static void main(String[] args) {
    
    
        //定义线程
        MyRunnable mt1 = new MyRunnable();
        MyRunnable mt2 = new MyRunnable();
        MyRunnable mt3 = new MyRunnable();
        MyRunnable mt4 = new MyRunnable();
        MyRunnable mt5 = new MyRunnable();
        MyRunnable mt6 = new MyRunnable();

        //利用Runnable接口子类对象来实例化Thread对象
        Thread thrad1 = new Thread(mt1,"线程1");
        Thread thrad2 = new Thread(mt2,"线程2");
        Thread thrad3 = new Thread(mt3,"线程3");
        Thread thrad4 = new Thread(mt4,"线程4");
        Thread thrad5 = new Thread(mt5,"线程5");
        Thread thrad6 = new Thread(mt6,"线程6");

        //启动线程
        thrad1.start();
        thrad2.start();
        thrad3.start();
        thrad4.start();
        thrad5.start();
        thrad6.start();
    }
}

operation result:
Insert picture description here

The difference between inheriting the Thread class and implementing the Runnable interface to complete multithreading

  • Implementing the Runnable interface can achieve resource sharing, but inheriting the Thread class cannot (such as ticket purchase issues)
  • Compared with inheriting the Thread class, implementing the Runnable interface has two major advantages: avoiding the limitations of single inheritance and sharing resources.
  • Compared with the inheritance of the Thread class, the Runnable interface is generally used to implement multithreading

3. Create threads through Callable and FutureTask

3.1 Create the implementation class of the Callable interface and implement its Call method
3.2 Use the FutureTask class to wrap the Callable object, this FutureTask object needs to encapsulate the return value of the Call method of the Callable object
3.3 Use the FutureTask object as the target of the Thread object to create and call the start method to start Thread


//1. 创建Callable接口的实现类 ,实现它的Call方法
class MyCallable<T> implements Callable<T>{
    
    

    //重写Callable的call方法
    @Override
    public T call() throws Exception {
    
    
        System.out.println(Thread.currentThread().getName() + "   ---->通过实现Callable接口来实现线程");
        return null;
    }
}


public class Callable_FutureTask {
    
    

    public static void main(String[] args) {
    
    

        //2. 实例化Callable对象
        Callable<Object> callable = new MyCallable<Object>();
        //3. 使用FutureTask类来包装Callable对象
        FutureTask<Object> futureTask = new FutureTask<Object>(callable);
        //使用FutureTask对象作为Thread对象的target创建并调用start方法启动线程
        Thread thread1 = new Thread((futureTask),"线程A");

        System.out.println("当前运行线程名:" + Thread.currentThread().getName());
        //启动线程
        thread1.start();
    }

}

operation result:

Insert picture description here

4. Multithreading through thread pool

class MyRunnable implements Runnable
{
    
    
    @Override
    public void run()
    {
    
    
        System.out.println("通过线程池的方式创建的线程,线程名 :" + Thread.currentThread().getName());

    }
}

public class ThreadPool {
    
    

    //设置线程池的数量
    private static int threadPoolNum = 8;


    public static void main(String[] args) {
    
    
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        for(int i = 0; i < threadPoolNum; i ++)
        {
    
    
            //创建线程对象
            MyRunnable thread = new MyRunnable();

            //Thread.sleep(1000);//使线程休眠1秒
            executorService.execute(thread);
        }
    }
}

operation result:
Insert picture description here

Notes on threads

  1. In java, all threads are started at the same time , which thread occupies CPU and other running resources, which thread can run.
  2. Every time a Java program runs, two threads need to be started ( main thread and garbage collector thread )
  3. While the Java thread is running, other threads will not end with the end of the main thread.

Guess you like

Origin blog.csdn.net/qq_40542534/article/details/108546957