Multithreading Basics (1) - Initial Thread

1. Thread concept

1.1 Threads and Processes

    A CPU can only process one process (program) at the same time, and a process contains at least one or more threads. The operating system allocates corresponding system resources, such as cpu, memory, etc., to each process, and all threads in the process These resources will be shared.

    Process: Each process has an independent code and data space (process context), and switching between processes will have a large overhead. A process contains 1--n threads. (A process is the smallest unit of resource allocation)

    Thread: The same type of thread shares code and data space, each thread has an independent running stack and program counter (PC), and the thread switching overhead is small. (Thread is the smallest unit of cpu scheduling)

1.2 Parallelism and Concurrency

    1. Parallel: true simultaneous operation

    2. Concurrency: All tasks are executed cyclically through the time slice allocation algorithm of the CPU, and the CPU constantly switches execution threads, causing the illusion of simultaneous operation.

1.3 Thread state

    1) New state (New): A thread object is newly created.

    2) Ready state (Runnable): After the thread object is created, other threads call the start() method of the object. Threads in this state are in the "runnable thread pool" and become runnable, just waiting to acquire the right to use the CPU. That is, except for the CPU, the process in the ready state has all the resources required to run.

    3) Running state (Running): The thread in the ready state obtains the CPU time slice and executes the program code.

    4) Blocked state (Blocked): The blocked state is that the thread gives up the right to use the CPU for some reason and temporarily stops running. Until the thread enters the ready state, there is no chance to go to the running state.

    5) Termination: When the thread run method executes to return, or an unhandled (try-catch) exception occurs, thread termination occurs.

    6) Waiting state: Indicates that the current thread enters the waiting state and needs to be notified or interrupted by other threads.

    7) Timeout waiting state: Indicates that the current thread enters the waiting state, and needs to be notified or interrupted by other threads, or it can automatically return after a certain period of time

Note: The waiting state, the timeout waiting state is actually a blocking state.

2. Simple thread code implementation

2.1 Created by inheriting the Thread class

    Inherit Thread, rewrite the run method and add task logic code in the run method to create a thread.

public class Demo2{
	public static void main(String[] args) {
		for(int i=0;i<=20;i++){
			test t=new test(i);
			t.start();
			System.out.println("main thread"+i);
		}
		
	}
	
}
class test extends Thread{
	int i;
	public test(int i){
		this.i=i;
	}
	//重写run方法
	@Override
	public void run(){
		System.out.println("new thread"+i);
	}
}

2.2 Implement the Runnable interface

public class Demo3 {
	public static void main(String[] args) {
        //实现Runnable 接口
		Runnable r=new Runnable() {
			@Override
			public void run() {
				System.out.println(Thread.currentThread().getName());
			}
		};
        //将Runnable对象作为参数传入Thread构造方法
		Thread t=new Thread(r);
		t.start();
	}
}

2.3 Implement the Callable interface

    This is a special method because it can get a return value or throw an exception, and neither Runnable nor Thread can, but the Callable thread task object can only be executed by the thread pool. Its return value is received by the Future object.

public class Demo5 {
	public static void main(String[] args) throws Exception {
		Callable<String> c=new Callable<String>() {
			@Override
			public String call() throws Exception {
				// TODO Auto-generated method stub
				return "callable";
			}
		};
		ExecutorService executors=Executors.newFixedThreadPool(5);
		Future<String> f=executors.submit(c);
		System.out.println(f.get());
	}
}

    The advantages of using Runnable, Callable interface implementation compared to inheriting the Thread class:

    1) Realize the decoupling of thread objects and thread tasks

    2) Avoid the problem of single inheritance of classes and obtain better extensibility

2.4 Simple use of thread pools

    Similar to the database connection pool, we dynamically generate and manage thread objects through a thread pool object (executor). Just pass in the thread task object (Runnable, Callable), and the thread pool object will automatically create or reuse thread objects. .

public class Demo4 {
	public static void main(String[] args) {
		//创建线程池对象,通过工厂类来创建线程池
		ExecutorService executors=Executors.newFixedThreadPool(5);//创建一个可重用的固定线程数的线程池
		Executors.newCachedThreadPool();//创建一个根据需要可随时创建新线程的线程池,当已经创建的线程中有可用的时便重用
		Executors.newSingleThreadExecutor();//创建一个使用单个线程的线程池,并以无界队列方式运行
		//调用方法提交线程任务并执行
		Runnable task=new Runnable() {
			@Override
			public void run() {
				System.out.println(Thread.currentThread().getName());
				
			}
		};
		executors.execute(task);
	}
}

Note: The submission and execution methods of Runnable and Callable objects are different. The Runnable object calls the execute method, while the Callable object calls the submit method.

 

 

 

Welcome to point out mistakes and deficiencies, thank you

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325445650&siteId=291194637