Multithreading knowledge 2 The most basic two ways to open threads

There are two common ways to implement multithreading

1. Implemented by inheriting the Thread class

class MyThread extends Thread {

	public void run() {
		System.out.println("current" + Thread.currentThread().getName() + "executing task");
	}
}

public class Test {

	public static void main(String[] args) {
		Thread t1 = new MyThread();
		t1.setName("A thread");
		t1.start();
		Thread t2 = new MyThread();
		t2.setName("B thread");
		t2.start();
	}
}
operation result:
The current B thread is executing the task
The current A thread is executing the task

  Note: After multiple runs, you will find that the displayed results will change each time and are different from the results we predicted. This is because when the CPU is executing, the allocation tasks are generally preemptive, and the thread is preempted and executed first. If you make the phenomenon you see more intuitive, you can use a loop in the run method

2. By implementing the Runnable interface

public class Test2 {

	public static void main(String[] args) {
		Runnable r = new MyThread2();
		Thread t1 = new Thread(r);
		t1.setName("A thread");
		t1.start();
		
		Thread t2 = new Thread(r);
		t2.setName("B thread");
		t2.start();
	}
}

class MyThread2 implements Runnable {

	public void run() {
		System.out.println("current" + Thread.currentThread().getName() + "executing task");
	}
}

 

Program running result: (It will be the same as above every time)
The current B thread is executing the task
The current A thread is executing the task

 3. Through the running results of the above two small programs, it is found that no matter which way to achieve multi-threading, the run() method must be rewritten, and the thread is started through the start() method, which will be executed after the start() method is executed. To the run() method, the run method is the entry point for the thread to perform tasks, but it should be noted that calling the start() method may not necessarily execute the run method immediately, because the multi-threaded runtime itself is preemptive, and each thread is preemptive. There is also a distinction between priorities and so on. Interested students can go to the API documentation, you will find that the two are substantially similar, and the Thread class also implements the Runnable interface.

4. Comparison of the two types of opening threads
a) The first type of thread opening code should be more concise
b) Opening a thread through an interface can avoid single inheritance
c) Opening a thread through an interface can realize multiple threads sharing a resource
usage principle: Use the interface as much as possible use interface

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327059718&siteId=291194637