You will understand after reading multi-thread

Overview of Multithreading Technology

process

​ Refers to an application running in memory, each process has an independent memory space

Thread

​ is an execution path in the process, sharing a memory space, threads can be switched freely, and concurrent execution. A process has at least one thread

​ Threads are actually further divided on the basis of processes. After a process is started, several execution paths inside can be divided into several threads



Thread scheduling

Time-sharing scheduling

​ All threads take turns to use the right to use the CPU, and evenly distribute the time that each thread occupies the CPU.

Preemptive scheduling

​ Give priority to threads with high priority to use the CPU. If the threads have the same priority, then one will be randomly selected (thread randomness). Java uses

Preemptive scheduling.

​ The CPU uses preemptive scheduling mode to switch between multiple threads at high speed. For a new core of the CPU, only one thread can be executed at a certain time, and the switching speed of the CPU between multiple threads is faster than we feel, and it seems to be running at the same time. In fact, multi-threaded programs cannot improve the running speed of the program, but it can improve the running efficiency of the program and make the CPU usage higher.

Synchronous and asynchronous

Synchronization : queued execution, inefficient but safe.

Asynchronous : synchronous execution, high efficiency but insecure data.

Parallel and concurrency

Concurrency : Refers to two or more events occurring in the same time period .

Parallel : Two or more events occur at the same time (simultaneously).

Enable multi-threading technology

1. Inherit Thread

public class MyThread extends Thread{
    
    
	/**
	 *run方法就是线程要执行的任务方法
	 */
	@Override
	public void run(){
    
    
		//这里的代码 就是一条新的执行路径.
		//这个执行路径的方式,不是调用run方法,而是通过Thread对象的start()来启动任务。
		for(int i=0;i<10;i++){
    
    
			System.out.println("锄禾日当午"+i);
		}
	}
}

public static void main(String[] args){
    
    
	MyThread m = new MyThread();
	m.start();
	for(int i=0;i<10;i++){
    
    
			System.out.println("汗滴禾下土"+i);
		}
}

Insert picture description here
Each thread has its own stack space and shares a heap memory
Insert picture description here

2. Implement Runnable

Implementing Runnable has the following advantages over inheriting Thread:

  1. Multithreading achieved by creating tasks and then assigning threads to threads is more suitable for situations where multiple threads perform the same task at the same time
  2. It can avoid the limitations of single inheritance.
  3. The task is separated from the thread itself, which improves the robustness of the program.
  4. The thread pool technology that we will learn later will accept Runnable type tasks but not Thread type threads.
public class MyRunnable implements Runnable{
    
        
	@Override    
	public void run(){
    
            
		//线程的任务        
		for(int i=0;i<10;i++){
    
                
			System.out.println("锄禾日当午"+i);        
		}    
	}
}

public static void main(String[] args){
    
        
	//实现Runnable    
	//1.    创建一个任务对象    
	MyRunnable r = new MyRunnable();    
	//2.    创建一个线程,并为其分配一个任务    
	Thread t = new Thread(r);    
	//3.    执行这个线程    
	t.start();    
	for(int i=0;i<10;i++){
    
               
		 System.out.println("锄禾日当午"+i);        
	}    
}

3. Callable with return worth thread

Runnable 与 Callable

接口定义
//Callable接口

	publicinterfaceCallable<V> {
    
    
		Vcall()throwsException;
		}
		
//Runnable接口
		
	public interface Runnable {
    
     		
		publicabstractvoidrun();
				
		}

Runnable is the same as Callable

    1.都是接口

​	2.都可以编写多线程程序

​	3.都采用Thread.start()启动线程

Runnable is different from Callable

	1.Runnable没有返回值;Callable可以返回执行结果

​	2.Callable接口的call()允许抛出异常;Runnable的run()不能抛出

Callable gets the return value

	Callalble接口支持返回执行结果,需要调用FutureTask.get()得到,
		此方法会阻塞主进程的继续往下执行,如果不调用不会阻塞。

Set and get the thread name

public static void main(String[] args){
    
    
	//如何获取线程的名称
			  System.out.println(Thread.currentThread().getName());
	newThread(new MyRunnable(),"锄禾日当午").start();
}


static class MyRunnable implements Runnable{
    
    
	@Override
	public void run(){
    
    
		System.out.println(Thread.currentThread().getName());
	}
}
public static void main(String[] args){
    
    
	//如何获取线程的名称
			  System.out.println(Thread.currentThread().getName());
	newThread(new MyRunnable(),"").start();
	newThread(new MyRunnable(),"").start();
	newThread(new MyRunnable(),"").start();
}


static class MyRunnable implements Runnable{
    
    
	@Override
	public void run(){
    
    
		System.out.println(Thread.currentThread().getName());
	}
}

Thread sleep

public static void main(String[] args){
    
    
	//线程的休眠 sleep
	for(int i=0;i<10;i++){
    
    
		System.out.println(i);
		Thread.sleep(1000);//休息一秒钟,指定时间休眠
	}
}

Clogging of threads

耗时操作

Thread interruption

public static void main(String[] args){
    
    
	//线程中断
	//一个线程是一个独立的执行路径,他是否应该结束,应该由自身决定
	//早期提供stop 过时,会直接插死
	
	
	
}
package thread;


public class Demo5 {
    
    
    public static void main(String[] args) {
    
    
        //线程中断
        //y一个线程是一个独立的执行路径,它是否结束应该由其自身决定
        Thread t1 = new Thread(new MyRunnable());
        t1.start();
        for (int i = 0; i < 5; i++) {
    
    
            System.out.println(Thread.currentThread().getName()+":"+i);
            try {
    
    
                Thread.sleep(1000);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }
        //给线程t1添加中断标记
        t1.interrupt();
    }

    static class MyRunnable implements Runnable{
    
    

        @Override
        public void run() {
    
    
            for (int i = 0; i < 10; i++) {
    
    
                System.out.println(Thread.currentThread().getName()+":"+i);
                try {
    
    
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
    
    
                    //e.printStackTrace();
                    System.out.println("发现了中断标记,线程自杀");
                    return;
                }
            }
        }
    }
}

Daemon thread

package thread;


public class Demo6 {
    
    
    public static void main(String[] args) {
    
    
        //线程分为守护线程和用户线程
        //用户线程:当一个进程不包含任何的存活的用户线程时,进行结束
        //守护线程:守护用户线程的,当最后一个用户线程结束时,所有守护线程自动死亡。
        Thread t1 = new Thread(new MyRunnable());
        //设置守护线程
        t1.setDaemon(true);
        t1.start();
        for (int i = 0; i < 5; i++) {
    
    
            System.out.println(Thread.currentThread().getName()+":"+i);
            try {
    
    
                Thread.sleep(1000);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }

    }

    static class MyRunnable implements Runnable{
    
    

        @Override
        public void run() {
    
    
            for (int i = 0; i < 10; i++) {
    
    
                System.out.println(Thread.currentThread().getName()+":"+i);
                try {
    
    
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace();
                }
            }
        }
    }
}

Guess you like

Origin blog.csdn.net/weixin_43515837/article/details/110941403