Multithreading - Concurrent Programming (2) - Open a new thread definition and instance with partial source code analysis

Part of the source code is explained in the comments of the code segment

After each Java program starts, a thread is opened by default, called the main thread (the thread where the main method is located)

Each thread is a java.lang.Thread object, and the current thread object can be obtained through the Thread.currentThread method

2 ways to start a thread

(1) Pass in a Runnable instance, and write the tasks that the child thread needs to perform in the run method

//第1种方法
public class Main {
	public static void main(String[] a) {
		Thread tj = new Thread(new Runnable() {
			@Override
			public void run() {//把线程想执行的任务写在run方法里即可
				System.out.println("新线程的名字 - "+Thread.currentThread().getName());
			}
		});
		tj.setName("汤键");//更改线程名称为“汤键”  不更改默认为Thread-0
		tj.setPriority(10);//更改线程优先级为10   不更改默认为普通优先级为5  线程优先级范围为1—10  数值越大优先级越高
		tj.start();//启动线程;Thread调用start方法后,内部会调用线程自己的run方法
	}
}//可用Lambda表达式优化

(2) Inherit the Thread class and override the run method

//第2种方法
class tt extends Thread{
	public void run() {
		//System.out.println("新线程的名字 - "+getName());  
		//使用getName()不会准确知道当前代码执行在哪一线程,只会返回new时内部分配的固定名称,它不会管你线程是否启动成功,都会分配这个名字
		System.out.println("新线程的名字 - "+Thread.currentThread().getName());
	}
}

public class Main {
	public static void main(String[] a) {
		Thread tj = new tt();
		tj.setName("汤键");
		tj.setPriority(10);
		tj.start();
		//直接调用run方法不调用start方法相当于没继承Thread,还是在主线程中执行,是错的
	}
}

Looking at the Thread source code, it can be seen that there is a native local method of start0 in the start method. It will apply for some resources to the CPU and the system. Only when the application is received will the run method be executed, and the thread will be really opened, which is the real multi-threading.

Guess you like

Origin blog.csdn.net/weixin_59624686/article/details/123929905