Use of Java multithreading

Before learning about multithreading, we should clarify three questions:

① What is thread?

A: when a program runs (process), it may contain multiple sequential execution streams, and each sequential execution stream is a thread.

② Is the relationship between, thread and process different?

A: threads are also called lightweight processes. A process can contain multiple threads. From the perspective of resource allocation, process is an independent unit for resource allocation and scheduling, and thread shares all resources in the parent process.

③ The role of multithreading?

A: multithreading can make the program concurrent, that is, within the same time interval, threads can be executed in turn, but the effect is the same as simultaneous execution.

There are three ways to create threads:

1. Inherit the thread class to create a thread class.

//通过继承Thread类来创建线程类
public class MyThread extends Thread {
	//线程共享资源(计数变量)
	private int count;

	@Override
	public void run() {
		for(;count<100;count++){
			System.out.println(getName() + " " + count);
		}
	}
		
	public static void main(String[] args) {
		for(int i=0;i<100;i++){
			System.out.println(Thread.currentThread().getName() + " " + i);		
			if(i == 20) {
				//创建并启动第一个线程
				new MyThread().start();
				//创建并启动第二个线程
				new MyThread().start();
			}
		}
	}

}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>