This article directory

  • Threads and multithreading

  • The running and creation of threads

  • Thread state

Threads and multithreading

What is a thread?

A Thread is an Object. For what? Java threads (also known as JVM threads) are tasks that allow multiple concurrent tasks within a Java process. Concurrent tasks within this process are called threads, which means at least one Thread in a process.

Java programs use multithreading mode to support a large number of concurrent request processing, if the program is executed in multithreading mode, its complexity is much higher than the single-thread serial execution. So multithreading: this is when the program (a process) runs with more than one thread.

Why multithreading?

  • Suitable for multi-core processors. With one thread running on one processor core, multiple threads can be distributed across multiple processor cores to make better use of multi-core processors.

  • Prevent blocking. Use multithreading technology (or message queue) to speed up code logic processing and shorten response time for operations with inconsistent data.

Talking about multithreading, most will talk about concurrency and parallelism, how to understand and distinguish the difference between these two?

  • Similar to a single CPU, through the CPU scheduling algorithm, etc., the ability to process multiple tasks, called concurrency

  • The ability of multiple cpus to simultaneously and simultaneously handle the same number of tasks is called parallelism

2 Thread running and creation

2.1 Creating threads

Java creates thread objects in two ways:

  • Inheriting the Thread class creates Thread objects

  • Implement the Runnable interface class to create thread objects

Create a MyThread object as follows:

@author Jeff Lee @bysocket.com * @since 2018年01月27日21:03:02*/ Public class MyThread extends Thread {@override // public void can be omittedrun() { System.out.println("Thread object of MyThread is performing a task"); } public static void main(String[] args) { for (int i = 0; i < 10; i++) { MyThread thread = new MyThread(); thread.start(); System.out.println("Thread object of MyThread"+ thread.getId()); }}}Copy the code

MyThread inherits the Thread object and overrides the run method to implement the Thread logic. The main function uses the for statement to loop through 10 threads, call the start method to start them, and print the ID of the current thread object.

What’s the difference between a run method and a start method?

The run method is called when the thread starts.

The start method means to start a new thread instance. The thread’s run method is invoked only after it has been started.

After executing main, the console prints the following:

The thread object of MyThread is performing a task. The thread object of MyThread 10MyThread is performing a task. The thread object of MyThread 11MyThread is performing a task The thread object of MyThread is performing a task. The thread object of MyThread is performing a task. The thread object of MyThread is performing a task 16MyThread's thread object is performing a task. 17MyThread's thread object is performing a task The thread object that is performing the task MyThread 19Copy the code

As you can see, the thread ID is the unique identifier of the thread. Each thread ID is different.

The relationship between the start and run methods is shown below:

Similarly, implementing the Runnable interface class to create thread objects is easy, but in a different form. Create MyThreadBrother as follows:

@author Jeff Lee @bysocket.com * @since 2018年01月27日21:22:57*/ Public class MyThreadBrother Implements Runnable {@override // public void can be omittedrun() { System.out.println("MyThreadBrother thread object performing a task"); } public static void main(String[] args) { for (int i = 0; i < 10; i++) { Thread thread = new Thread(new MyThreadBrother()); thread.start(); System.out.println("Thread object of MyThreadBrother"+ thread.getId()); }}}Copy the code

Code: “Java-concurrency -core-learning”

https://github.com/JeffLi1993/java-concurrency-core-learning

2.1 Running of threads

After running the two small demos above, the JVM executes the main thread and then creates a new thread in the main thread. Normally, all threads execute until the end of the run. Terminates unless system.exit (1) is called in a thread.

In real development, a request-to-response is a thread. But in this thread, you can use the thread pool to create new threads to perform tasks.

3 Status of the thread

Create a new MyThreadInfo class and print the thread object properties as follows:

@author Jeff Lee @bysocket.com @author Jeff Lee @bysocket.com @author Jeff Lee @Bysocket.com @author Jeff Lee @Bysocket.com @author Jeff Lee @Bysocket.com @override // public void can be omittedrun() { System.out.println("Thread instance of MyThreadInfo is performing a task"); // System.exit(1); } public static void main(String[] args) { MyThreadInfo thread = new MyThreadInfo(); thread.start(); System.out.print("Thread object for MyThreadInfo" + "Thread unique identifier:" + thread.getId() + "" + "Thread name:" + thread.getName() + "" + "Thread status:" + thread.getState() + "" + "Thread priority:" + thread.getPriority()); }}Copy the code

The execution code is printed as follows:

Thread object of MyThreadInfo Thread UNIQUE identifier: 10 Thread name: thread-0 Thread status: NEW Thread priority: 5Copy the code

A thread is an object with unique identifier ID, name, status, priority, and other attributes. A thread can only modify its attributes such as priority and name, but cannot modify its ID or status. The ID is assigned by the JVM and the default name is Thread-xx, where XX is a set of numbers. The initial state of the thread is NEW.

Thread priorities range from 1 to 10, with 1 being the lowest priority and 10 the highest priority. It is not recommended to change the priority of a thread. You can change the priority to the highest or lowest level if necessary.

Thread states are implemented through the thread. State constant class. There are six Thread states: New, runnnable, blocked, waiting, time waiting, and terminated. The state transition diagram is as follows:

The thread state flow is as follows:

  • After the thread is created, it enters the new state

  • Call the start or run method to enter the runnable state

  • The JVM executes threads in runnable state by thread priority, time slice, etc. When the execution starts, it enters the running state

  • If the thread performs sleep, wait, join, IO block, etc. Enter the wait or Blocked state

  • After the thread completes execution, the thread is removed from the thread queue. The last state is terminated.

4 summary

This article introduces the thread and multithreading foundation, including the thread start and thread state. In the next article, we’ll talk about how threads work. Including interruption, termination, etc

Code: “Java-concurrency -core-learning”

https://github.com/JeffLi1993/java-concurrency-core-learning

Recommend an exchange learning group: 697579751, which will share some veteran architects recorded video: Spring, MyBatis, Netty source code analysis, high concurrency, high performance, distributed, microservice architecture principle, JVM performance optimization these become the architect’s necessary knowledge system. You can also receive free learning resources, which have benefited a lot at present: