preface

Spent the previous week reviewing Java collections:

  • The Collection overview
  • List collection is as simple as that.
  • Map sets, hash tables, and red-black trees
  • HashMap is as simple as this
  • LinkedHashMap is as simple as this
  • TreeMap is that simple
  • ConcurrentHashMap is analyzed based on JDK1.8 source code
  • Set sets are that simple!
  • Java set summary [interview questions + brain map], will be a net of knowledge!

Before writing the article, I read through the concurrent chapter of Java Core Technology Volume 1 and the previous part of Java Concurrent Programming Practice, and reviewed the notes I had written before. From today to enter the knowledge of multithreading

Before learning the Java foundation when learning multithreading foundation or very serious, but in the back has not reviewed it, as time goes by it is almost forgotten.. In learning JavaWeb also has not been to the multithreading place (I do things too water…) .

Because this part of the interview is a large proportion, and learning multithreading is also very helpful for my future promotion (I think).

In fact, I am also equivalent to learning multi-threading from scratch, if the article is wrong, please also include more, don’t be afraid to point out in the comments area ~~

First, understanding multithreading

1.1 Introduction to Processes

Speaking of threads, we have to mention processes

Open task Manager under Windows, you can find that we run programs on the operating system are processes:

Process definition:

Process is a program execution, process is a program and its data in the processing machine sequential execution of the activities, process is an independent function of the program in a data set running process, it is the system for resource allocation and scheduling of an independent unit

  • A process is an independent unit of the system for resource allocation and scheduling. Each process has its own memory space and system resources

1.2 Back to Threads

The system has such a concept of process, process has been able to carry out resource allocation and scheduling, why thread?

To enable concurrent execution of programs, the system must perform the following operations:

  • (1) to create a process, the system to create a process, it must allocate its necessary, in addition to the processor of all resources, such as memory space, I/O equipment, and the establishment of the corresponding PCB;
  • (2) Cancel the process. When canceling the process, the system must reclaim the resources occupied by it first, and then cancel the PCB;
  • (3) Process switching. When context switching is performed on the process, the CPU environment of the current process needs to be retained and the CPU environment of the newly selected process needs to be set, so it takes a lot of processor time.

It can be seen that process scheduling, dispatching and switching in multi-processor environment need to spend a lot of time and space overhead

The main purpose of introducing thread is to improve the execution efficiency of the system, reduce the idling time of the processor and the time of scheduling switch, and facilitate system management. ** Makes OS have better concurrency

  • Simply put: multi-processing for processes is cpu-intensive, and we introduced threads as the basic unit of scheduling and dispatching (replacing some of the basic functions of processes ** [scheduling] **).

So where is the thread? Here’s an example:

In other words, multiple tasks can be executed in the same process, and each task can be identified as a thread.

  • So: a process can have 1 or more threads!

1.3 Processes and Threads

So we can conclude:

  • Processes serve as the basic unit of resource allocation
  • Thread, as the basic unit of resource scheduling, is the execution unit of the program and the execution path (single-thread: one execution path, multi-thread: multiple execution paths). Is the basic unit of CPU used by a program.

Threads have three basic states:

  • Execute, ready, block

Threads have five basic operations:

  • Derive, block, activate, schedule, end

Thread properties:

  • 1) Light entities;
  • 2) Basic unit of independent dispatch and dispatch;
  • 3) Concurrent execution;
  • 4) Sharing process resources.

There are two basic types of threads:

    1. User-level thread: the management process is completed by the user program, the operating system core only manages the process.
    1. System-level threads (core-level threads) : Managed by the operating system kernel. The operating system kernel provides system calls and application program interfaces (apis) to applications that allow users to create, execute, and undo threads.

It is worth noting that the existence of multithreading is not to improve the execution speed of the program. In fact, in order to improve the utilization rate of the application, the execution of the program is actually robbing the CPU resources, CPU execution right. Multiple processes compete for this resource, and if one of them has more paths, it has a higher chance of stealing execution from the CPU

1.4 Parallelism and Concurrency

In parallel:

  • Parallelism is when two or more events occur at the same time.
  • Parallelism is multiple events on different entities

Concurrent:

  • Concurrency is the occurrence of two or more events at the same time interval.
  • Concurrency is multiple events on the same entity

It follows that parallelism is for processes and concurrency is for threads.

1.5Java multithreading

It says a lot of basic, understanding stuff. Let’s go back to Java and see how Java implements multithreading

Java implements multithreading using the Thread class. Let’s look at the top comment of the Thread class:

As you can see from the top comment above, there are two ways to create multiple threads:

  • Inherit Thread and override the run method
  • Implement the Runnable interface, rewrite the run method

Inherit Thread and override the run method

Create a class that inherits Thread and overrides the run method


public class MyThread extends Thread {

	@Override
	public void run(a) {
		for (int x = 0; x < 200; x++) { System.out.println(x); }}}Copy the code

Let’s call the test to see:


public class MyThreadDemo {
	public static void main(String[] args) {
		// Create two thread objects
		MyThread my1 = new MyThread();
		MyThread my2 = newMyThread(); my1.start(); my2.start(); }}Copy the code

1.5.2 Implement Runnable interface, rewrite run method

Implement the Runnable interface, rewrite the run method


public class MyRunnable implements Runnable {

	@Override
	public void run(a) {
		for (int x = 0; x < 100; x++) { System.out.println(x); }}}Copy the code

Let’s call the test to see:


public class MyRunnableDemo {
	public static void main(String[] args) {
		// Create an object of class MyRunnable
		MyRunnable my = new MyRunnable();

		Thread t1 = new Thread(my);
		Thread t2 = newThread(my); t1.start(); t2.start(); }}Copy the code

The result is still the same as above, I will not map here ~~~

1.6Java multithreading needs to pay attention to the details

Don’t confuse run() with start()

The run() and start() methods differ:

  • run(): justEncapsulate code executed by threadsDirect calls are normal methods
  • start(): first of all,Started the threadAnd thenIt is up to the JVM to call the thread’s run() method.

Is the JVM started single-threaded or multi-threaded?

  • It’s multithreaded. Not only will the main thread be started, but the garbage collection thread will at least be started. Otherwise, who will help you reclaim unused memory

So, since there are two ways to implement multithreading, which one do we use??

Generally we use the implementation Runnable interface

  • You can avoid the restriction of single inheritance in Java
  • We should decouple concurrent running tasks from the running mechanism, so we chose to implement the Runnable interface instead!

Second, the summary

This article mainly explains what the thread is, to understand the basis of the thread for our future learning is helpful. This is basically a simple entry into a door

The next article will focus on the API of Thread. This article will focus on the API of Thread

Using threads can actually lead to data insecurity and even program failure, which will be discussed later

Before learning the operating system according to the “Computer operating system – Tang Xiaodan” this book also made a little note, are relatively simple knowledge points. May be helpful to everyone ~

  • Operating system 1 [Introduction]
  • Operating System Part 2 [Process Management]
  • Operating System Part 3 threads
  • Operating system chapter 4 [Processor scheduling]
  • Operating System Chapter 5 [Deadlock]
  • Operating System Chapter 6 [Memory Management]
  • Operating System Part 7 Device Management

References:

  • Java Core Technology Volume 1
  • Java Concurrent Programming
  • Computer Operating System – Dennis Tang

If the article has the wrong place welcome to correct, everybody exchanges with each other. Students who are used to reading technical articles on wechat and want to get more Java resources can follow the wechat public account :Java3y.

Open source project (6 K STAR) :Github.com/ZhongFuChen…

If you want to follow my updated articles and shared dry goods in real time, you can search Java3y on wechat.

The content of the PDF document is typed by hand. If you don’t understand anything, you can ask me directly (the official account has my contact information).