当前位置:网站首页>Summary of thread implementation

Summary of thread implementation

2022-07-06 14:37:00 Floating~

Tips : Before reading this article , Please first understand the basic concepts of threads and processes in the operating system .

The basic concept of thread will be mentioned in this article , Please refer to my two notes for operating system and process   https://note.youdao.com/s/ag3ipekEicon-default.png?t=M4ADhttps://note.youdao.com/s/ag3ipekE

            
https://note.youdao.com/s/BFTOv61yicon-default.png?t=M4ADhttps://note.youdao.com/s/BFTOv61y

Catalog

Preface :

One 、 The basics of multithreading

 1.1 What is thread

 1.2 When multithreading is needed

 1.3 The advantages and disadvantages of multithreading

 1.4 Multithreaded species state

Two 、 Thread implementation

 2.1 Inherit Thread class      

 2.2 Realization Runnable Interface

 2.3 Realization Callable Interface  

 2.4 Thread pool


Preface :

At the system level , In order to reduce the time-consuming operation , Improve the efficiency of program parallel operation and CPU Utilization ratio , We introduced the technical concept of multithreading .、

This article will start with the basic concept of thread , Introduce in detail the four ways to create multithreading .

One 、 The basics of multithreading

 1.1 What is thread

        A thread is an executable unit inside a process , It is a sequence control process that can complete an independent task , If you run multiple threads in a process at the same time , To do different things , It's called multithreading .

 1.2 When multithreading is needed

        (1) When the program needs to perform two or more tasks at the same time .

        (2) When the program needs to perform some tasks that need to wait , For example, user registration , File read and write .

        (3) When the background execution program is required .

 1.3 The advantages and disadvantages of multithreading

         advantage :

  • It can appropriately improve the execution efficiency of the program
  • Can properly improve the utilization rate of resources (cpu、 Memory utilization )

         shortcoming :

  • Starting a thread requires a certain amount of memory space ,( By default , The main thread 1M, Sub thread 512KB), If you start a lot of threads , It takes up a lot of memory space , Reduce the performance of the program .
  • More threads ,cpu The higher the overhead on the scheduling thread .
  • Programming is more complicated : For example, the communication between threads 、 Multithreaded data sharing

 1.4 Multithreaded species state

  1. NEW: New state . When a thread is created , Before starting , In that state .
  2. RUNNABLE: Operational state . When a thread is executing a task , In that state .
  3. WAITING: Infinite waiting state . A thread gets Lock Lock object , Failure , In that state .
  4. TIMED_WAITING: Time waiting state . When a thread is executing sleep Method time , In that state .
  5. BLOCKED: Blocked state . A thread gets synchronized( Code block 、 Method ) Lock object , Failure , In that state .
  6. TERMINATED: Die state . When the thread finishes executing the task , In that state .

among NEW State and TERMINATED The status will only appear once .
 

Two 、 Thread implementation

Creating a sub thread is : establish Thread Object of type , And start execution . 

 2.1 Inherit Thread class      

        Thread class :
                   Package :java.lang;
                   Construction method :
                      public Thread();
                      public Thread(Runnable target);
                      public Thread(Runnable target,String name);
                   Static methods :
                      static Thread currentThread();// Get the current thread , Which thread executes the method , Just get which thread
                   Member method :
                      void start();// It can only be called once , Cannot call more than once
                      void run();// After the thread starts , Will execute run The code in the method
                      String getName();// Get the name of the thread
                      void setName(String name);// Set the name of the thread   

  Inherit Thread The steps to create a thread of class are as follows :

  1. Create an inheritance from Thread Subclasses of classes .
  2. rewrite Thread Class run Method –> Declare the operation performed by this thread in run() in .
  3. Create subclass objects .
  4. Called by subclass object start() Method .

  establish Thread Class object , rewrite run() The code of the method is as follows :

public class Test01Thread {
	public static void main(String[] args) {
		// Create... As an anonymous inner class Thread Object of type , Create thread 
		Thread t = new Thread() {
			@Override
			public void run() {
				String name = Thread.currentThread().getName();
				System.out.println(name);
			}
		};
		t.start();// Start thread 
		
	};

}

 

 2.2 Realization Runnable Interface

        Runnable Interface :

                Runnable Than Thread The advantages of class :
                  1. You can avoid java The limitations of single inheritance in (java It is single inheritance and multi-level inheritance , And implementation is multi implementation
                  2. Task and thread separation , Realize understanding coupling
                  3. Thread pool can only be passed in Runnable perhaps Callable Object of type , You cannot use inheritance

  Realization Runnable The steps to create a thread for the interface are as follows : 

  1. Create an implementation Runnable The class of the interface
  2. Realization Runnable Methods in interfaces .
  3. Create objects that implement classes .
  4. Pass this object as an argument to Thread In the constructor of class , establish Thread Class object .
  5. adopt Thread Class object call start() Method .

   Realization Runnable The code of the interface creation thread is as follows :

public class Test02Runnable {
	public static void main(String[] args) {
		// Use anonymous inner classes to create Runnable Object of type 
		Runnable r = new Runnable() {
			@Override
			public void run() {
				String name = Thread.currentThread().getName();
				System.out.println(name);
			}
		};
		
		// Create thread 
		Thread t = new Thread(r," Threads 1");
		t.start();
	}

}

 

 2.3 Realization Callable Interface  

         callable Interface :

  Realization Callable The interface steps are as follows :

  1. Create subclass implementation callable Implementation class of .
  2. Realization call Method , Declare the operation that this thread needs to perform in call In the method .
  3. establish Callable Interface object
  4. Put this Callable The object of the implementation class is passed as a parameter to FutureTask The constructor , establish FutureTask object .
  5. take FutureTask The order of the class is passed to Thread In the constructor of class , establish Thread Class object , Start the thread through this object
  6. Can get Callable Implementation class call Return value of method .( Optional , If you need a return value get, No need, no get)   
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

public class Test03Callable {
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		// Create by anonymous inner class Callable Object of type 
		Callable<String> callable = new Callable<String>() {
			@Override
			public String call() throws Exception {
				System.out.println(Thread.currentThread().getName());
				return " There are return values ";
			}
		}; 
		
		// establish FutureTask The object accepts callable Return value result 
		FutureTask<String> ft=new FutureTask(callable);
		
		// Create thread 
		Thread t=new Thread(ft);
		
		// Start thread 
		t.start();
		// Get the return result of the thread 
		String str = ft.get();
		
		System.out.println(str);// test Callable The return value of 
	}

}

 2.4 Thread pool

        Thread pool creates threads :
          advantage :
             1. Reduce resource consumption ( Reduce the frequent creation and destruction of threads ).
                   Threads in the thread pool can be created in advance , And you can only finish the task without destroying
             2. Improve response time . Threads in the thread pool can create threads in advance .
             3. Improve the manageability of threads .( There are many tasks , And each task takes a long time )
               Creating a thread takes about 1M Space .
  
           grammar :
              Executors class
                  static ExecutorService newFixedThreadPool(int c);// The parameter is the number of threads
  
              ExecutorService Interface :
                  void execute(Runnable r);
                  Future<?> submit(Runnable r);// If the thread returns a value after executing the task , You can process the returned results
                  <T> Future<T> submit(Callable<T> c);
                  void shutdown();// Close thread pool
  
              Future<T> Interface
                  T get();// You must wait for the execution of the subthread task to end , To get the returned result .

  Realization Runnable Interface , Create threads with thread pool . 

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test04Executors {
	public static void main(String[] args) {
		// Create a fixed thread pool object ,2 Create two threads for .
		ExecutorService threadPool = Executors.newFixedThreadPool(2);
		
		Runnable r = new Runnable() {
			@Override
			public void run() {
				System.out.println(Thread.currentThread().getName());
			}
		};
		
		// Perform tasks 
		threadPool.execute(r);
		
		// close 
		threadPool.shutdown();
	}

}

  Realization Callable Interface , Create threads with thread pool , And get the return value .

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Test05ExecutorsCall {
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		// Create thread pool object 
		ExecutorService threadPool = Executors.newFixedThreadPool(1);
		
		// Create by anonymous inner class Callable Object of type 
		Callable<String> callable = new Callable<String>() {
			@Override
			public String call() throws Exception {
				System.out.println(Thread.currentThread().getName());
				Thread.sleep(10000);
				return " There is a return value ";
			}
		}; 
		
		// Perform tasks 
		Future<String> future = threadPool.submit(callable);
		// Get the return result of the thread .
		String str = future.get();
		
		System.out.println(str);// test Callable The return value of 
		
		// close 
		threadPool.shutdown();
	}

}

 

 

Last , Thank you for your continued support !!!

Learn from time to time , To make progress .

 

 

原网站

版权声明
本文为[Floating~]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060918448968.html