Multithreading uses and cases

1. What is a process? What is a thread?
A process is: an application (1 process is a software).

A thread is: an execution scenario/execution unit in a process.

Note: A process can start multiple threads.
eg: For java programs, when entering in the DOS command window:
java HelloWorld and press Enter. The JVM will be started first, and the JVM is a process.

The JVM then starts a main thread and calls the main method ( the main method is the main thread ).
At the same time, a garbage collection thread is started to take care of and collect garbage.

At the very least, there are at least two concurrent threads in current Java programs, one is the garbage collection thread , and the other is the main thread that executes the main method.

2. What is the relationship between processes and threads?
Process: It can be seen as a company in real life.

Thread: can be regarded as an employee in the company.

Note: The memory
of process A and process B is independent and not shared .
eg: Warcraft game is a process
and Kugou Music is a process.
These two processes are independent and do not share resources.

3. For a single-core CPU, can true multi-thread concurrency be achieved?
For multi-core CPU computers, true multi-thread concurrency is no problem. A 4-core CPU means that at the same point in time, 4 processes can actually be executed concurrently.

A single-core CPU means there is only one brain:
it cannot achieve true multi-thread concurrency, but it can give people a feeling of "multi-thread concurrency".

For a single-core CPU, it can actually only process one thing at a certain point in time. However, due to the extremely fast processing speed of the CPU, multiple threads frequently switch between executions, giving others the impression that there are multiple things. Doing it at the same time! ! !

4. What is true multi-thread concurrency?

The t1 thread executes t1.
The t2 thread executes t2.
t1不会影响t2,t2也不会影响t1. This is called true multi-threaded concurrency.

Thread construction method

First way:

Write a class, inherit Thread , override run方法 .

  1. How to create a thread object? new inherits the thread class.
  2. How to start the thread? Call  start() the method of the thread object.
// 定义线程类
public class MyThread extends Thread{
	public void run(){
	
	}
}
// 创建线程对象
MyThread t = new MyThread();
// 启动线程。
t.start();
public class ThreadTest02 {
    public static void main(String[] args) {
        MyThread t = new MyThread();
        // 启动线程
        //t.run(); // 不会启动线程,不会分配新的分支栈。(这种方式就是单线程。)
        t.start();
        // 这里的代码还是运行在主线程中。
        for(int i = 0; i < 1000; i++){
            System.out.println("主线程--->" + i);
        }
    }
}

class MyThread extends Thread {
    @Override
    public void run() {
        // 编写程序,这段程序运行在分支线程中(分支栈)。
        for(int i = 0; i < 1000; i++){
            System.out.println("分支线程--->" + i);
        }
    }
}

Notice:

t.run() does not start a thread, it is just a normal method call. No new branch stack will be allocated .

The function of the t.start() method is to start a branch thread and open up a new stack space in the JVM. After the task of this code is completed, it ends instantly.
The task of this code is just to open a new stack space. As long as the new stack space is opened, the start() method is over. The thread is started successfully.
A successfully started thread will automatically call the run method, and the run method is at the bottom of the branch stack (push).
The run method is at the bottom of the branch stack, and the main method is at the bottom of the main stack. run and main are of the same level.

Ticket selling case:

package com.example;
 
import sun.security.krb5.internal.Ticket;
 
public class MyThreadTickerSell {
    public static void main(String [] args){
    new TicketWindow().start(); //创建一个线程对象TicketWindow并开启
        new TicketWindow().start(); //创建一个线程对象TicketWindow并开启
        new TicketWindow().start(); //创建一个线程对象TicketWindow并开启
        new TicketWindow().start(); //创建一个线程对象TicketWindow并开启
    }
}
 
 
class TicketWindow extends Thread{
    private int ticket = 100;
    public void run() {
        while (true){
 
            if(ticket>0){
                Thread th = Thread.currentThread(); //获取当前线程
                String th_name = th.getName();//获取当前的线程的名字
                System.out.println(th_name+"正在发售第:"+ticket--+"张票");
            }
        }
    }
 
}

Second way:

Write a class, implement java.lang.Runnable  the interface, and implement itrun方法 .

  1. How to create a thread object? The new thread class passes in the runnable class/interface.
  2. How to start the thread? Call  start() the method of the thread object.
// 定义一个可运行的类
public class MyRunnable implements Runnable {
	public void run(){
	
	}
}
// 创建线程对象
Thread t = new Thread(new MyRunnable());
// 启动线程
t.start();
public class ThreadTest03 {
    public static void main(String[] args) {
        Thread t = new Thread(new MyRunnable()); 
        // 启动线程
        t.start();
        
        for(int i = 0; i < 100; i++){
            System.out.println("主线程--->" + i);
        }
    }
}

// 这并不是一个线程类,是一个可运行的类。它还不是一个线程。
class MyRunnable implements Runnable {
    @Override
    public void run() {
        for(int i = 0; i < 100; i++){
            System.out.println("分支线程--->" + i);
        }
    }
}

Note:
The second way to implement interfaces is more common, because if a class implements the interface, it can also inherit other classes, which is more flexible.

Case:

package com.example;
 
public class MyRunnableTest {
    public static void main (String [] args){
     TicketWindow tw = new TicketWindow();//创建TicketWindow实例化对象
        new Thread(tw,"窗口1").start();//创建线程对象并且命名窗口1,开启线程
        new Thread(tw,"窗口2").start();//创建线程对象并且命名窗口2,开启线程
        new Thread(tw,"窗口3").start();//创建线程对象并且命名窗口3,开启线程
        new Thread(tw,"窗口4").start();//创建线程对象并且命名窗口4,开启线程
    }
}
 
class TicketWindow implements  Runnable{
    private int ticket=100;
    public void run(){
        while (true){
            if(ticket>0){
                Thread th = Thread.currentThread();//获取当前线程
                String th_name = th.getName();//获取当前线程的名字
                System.out.println(th_name+"正在发售第:"+ticket--+"张票");
            }
        }
 
    }
 
}

5. Thread’s sleep method

 

(1) Static method: Thread.sleep(1000);
(2) The parameter is milliseconds
(3) Function: Let the current thread go to sleep and enter the "blocked state", giving up the CPU time slice and letting it be used by other threads.
                     If this line of code appears in thread A, thread A will go to sleep.
                     If this line of code appears in thread B, thread B will go to sleep.
(4) The Thread.sleep() method can achieve this effect:
         execute a specific piece of code at a specific time interval, and execute it at how often.
 

public class ThreadTest06 {
    public static void main(String[] args) {
    	//每打印一个数字睡1s
        for(int i = 0; i < 10; i++){
            System.out.println(Thread.currentThread().getName() + "--->" + i);

            // 睡眠1秒
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Guess you like

Origin blog.csdn.net/WJY898989/article/details/128365498