Thread and multi-thread interviews in April 2018 are mandatory and mandatory in April 2018

Source: Internet
Author: User

Thread and multi-thread interviews in April 2018 are mandatory and mandatory in April 2018

Contents

  • Thread and Multithreading

  • Thread running and Creation

  • Thread status

1 thread and Multithreading

What is a thread?

A Thread is an Object ). What is it? A Java thread (also known as a JVM thread) is a Java Process that allows multiple concurrent tasks. Concurrent tasks in the process become threads, and at least one Thread in the process.

Java programs use multithreading to support a large number of concurrent request processing. If a program is executed in multiple threads, the complexity is much higher than that of single-thread serial execution. So multithreading: This program (a process) runs with more than one thread.

Why is multithreading used?

  • Suitable for multi-core processors. A thread runs on a processor core, so multithreading can be allocated to multiple processor cores to make better use of multi-core processors.

  • Prevent blocking. Use multi-thread technology (or Message Queue) to accelerate code logic processing and shorten response time for operations with poor data consistency.

When talking about multithreading, We will mostly talk about concurrency and parallelism. How can we understand and differentiate the two differences?

  • Similar to a single CPU, the CPU scheduling algorithm is used to process multiple tasks, which is called concurrency.

  • Similar to multiple CPUs, and the ability to process the same number of tasks at the same time is called parallel

2. thread running and Creation

2.1 thread Creation

There are two ways to create a thread object in Java:

  • Inherit the Thread class to create a Thread object

  • Implement the Runnable interface class to create a thread object

Create a MyThread object with the following code:

/*** Inherit the Thread class to create a Thread object * @ author Jeff Lee @ bysocket.com * @ since January 27, 2018 21:03:02 */public class MyThread extends Thread {@ Override // public void run () {System. out. println ("MyThread thread object is executing the task");} public static void main (String [] args) {for (int I = 0; I <10; I ++) {MyThread thread = new MyThread (); thread. start (); System. out. println ("MyThread thread object" + thread. getId ());}}}

The MyThread class inherits the Thread object and Override the run method to implement the logic in the Thread. The main function uses the for statement to create 10 threads cyclically, call the start method to start the thread, and print the ID of the current thread object.

What is the difference between the run and start methods?

The run method indicates running. After the thread is started, the run method is called.

The start method means to start a new thread instance. After the thread is started, the run method of the thread is called.

After the main method is executed, the console prints the following:

MyThread thread object is executing task MyThread thread object 10 MyThread thread object is executing task MyThread thread object 11 MyThread thread object is executing task MyThread thread object 12 MyThread thread object the thread object of the MyThread object 13 MyThread is executing the task MyThread thread object 14 the thread object of MyThread is executing the task MyThread thread object 15 the thread object of MyThread is executing the task MyThread thread object 16 MyThread thread object is executing the task MyThread thread object 17 MyThread thread object is executing the task MyThread thread object 18 MyThread thread object is executing the task MyThread thread object 19

It can be seen that the thread ID is the unique identifier of the thread, and each thread ID is different.

Relationship between the start method and the run method:

Similarly, it is easy to implement the Runnable interface class to create a thread object, just in different forms. The code for creating MyThreadBrother is as follows:

/*** Implement the Runnable interface class to create a thread object * @ author Jeff Lee @ bysocket.com * @ since January 27, 2018 21:22:57 */public class MyThreadBrother implements Runnable {@ Override // public void run can be omitted () {System. out. println ("MyThreadBrother's thread object is executing 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 ("MyThreadBrother thread object" + thread. getId ());}}}

Code details: "java-concurrency-core-learning 」

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

2.1 thread running

After running the preceding two demos, JVM executes the main function thread and creates a new thread in the main thread. Under normal circumstances, all threads are executed until the end of the operation. Unless System. exit (1) is called in a thread, it is terminated.

In actual development, a request to a response is a thread. However, in this thread, you can use the thread pool to create a new thread to execute tasks.

3. thread status

Create a new MyThreadInfo class and print the attributes of the thread object. The Code is as follows:

/*** Attribute value of the Thread Instance Object * @ author Jeff Lee @ bysocket.com * @ since January 27, 2018 21:24:40 */public class MyThreadInfo extends Thread {@ Override // public void run () can be omitted () {System. out. println ("the thread instance of MyThreadInfo is executing the task"); // System. exit (1);} public static void main (String [] args) {MyThreadInfo thread = new MyThreadInfo (); thread. start (); System. out. print ("MyThreadInfo thread object" + "unique thread identifier:" + thread. getId () + "" + "thread name:" + thread. getName () + "" + "thread status:" + thread. getState () + "" + "thread priority:" + thread. getPriority ());}}

The Execution Code is printed as follows:

The Thread instance of MyThreadInfo is executing the job. The unique identifier of the Thread object of MyThreadInfo: 10 Thread name: Thread-0 Thread status: NEW Thread priority: 5

A thread is an object that has attributes such as ID, name, status, and priority. A thread can only modify attributes such as its priority and name, but cannot modify its ID and status. ID is assigned by JVM. The default name is Thread-XX, and XX is a group of numbers. The initial state of the thread is NEW.

The thread priority ranges from 1 to 10, where 1 is the lowest priority and 10 is the highest priority. It is not recommended to change the thread priority. If the business needs it, You can naturally modify the thread priority to the highest or lowest.

The Thread status is implemented through Thread. the State constant class has six thread states: new, runnnable, blocked, waiting, and time waiting) and terminated ). The status transition diagram is as follows:

The thread status process is roughly 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 runnable threads Based on the thread priority and time slice. When execution starts, it enters the running state.

  • If the thread executes sleep, wait, join, or IO blocking. Enter the wait or blocked status

  • After the thread is executed, the thread is removed from the thread queue. The final state is terminated.

4. Summary

This article describes the basics of threads and multithreading, including thread startup and thread status. Next we will talk about the specific operations of the thread. Including interruptions and Termination

Code details: "java-concurrency-core-learning 」

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

We recommend a communication learning group:650385180Some video recordings recorded by senior architects include Spring, MyBatis, Netty source code analysis, high concurrency, high performance, distributed, and microservice architecture principles, JVM performance optimization is a required knowledge system for architects. You can also get free learning resources, which has benefited a lot:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.