Mason Chat Concurrent Programming: Threads and multithreading must Know (Basic)

Source: Internet
Author: User
Tags thread class

Directory of this document

    • Threading and multithreading
    • Running and creating a thread
    • The state of the thread
1 Threads and multithreading

What is a thread?
A thread is an object. For what? A Java thread (also known as a JVM thread) is a task that allows multiple simultaneous tasks within a Java process. The concurrent tasks within the process become threads (thread), and at least one thread in a process.

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

Why use multithreading?

    • Suitable for multi-core processors. A thread runs on a processor core, so multiple threads can be assigned to multiple processor cores, making better use of multicore processors.
    • Prevent blocking. Using multithreaded technology (or Message Queuing) to speed up the processing of code logic and shorten response time is not a strong data consistency operation.

Talk to multi-threading, probably talk about concurrency and parallelism, how to understand and distinguish between the two differences?

    • Like a single CPU, through the CPU scheduling algorithm, etc., the ability to handle multiple tasks, called concurrency
    • Similar to multiple CPUs, and the ability to process the same multiple tasks, called parallel
2 thread runs with creation of 2.1 threads

There are two ways in which Java creates thread objects:

    • Inheriting the thread class to create a threading object
    • Implementing the Runnable interface class to create a thread object

Create a new MyThread object with the following code:

/*** Inherit thread class to create threading object * @authorJeff Lee @ bysocket.com * @sinceJanuary 27, 2018 21:03:02 */ Public classMyThreadextendsThread {@Override //Can be omitted     Public void Run() {System. out.println("MyThread thread object is performing a task"); } Public Static void Main(string[] args) { for(inti =0; I <Ten; i++) {MyThread thread =New MyThread(); Thread.Start(); System. out.println("MyThread Thread Object"+ Thread.getId()); }    }}

The MyThread class inherits the thread object and overrides the Run method to implement the logic inside the thread. The main function is to use the For statement, looping through the creation of 10 threads, calling the Start method to start the thread, and finally printing the ID of the current thread object.

What is the difference between the Run method and the Start method?
The Run method is meant to run, and the Run method is called after the thread has started.
The Start method is the starting point, which is to start a new thread instance. The thread's Run method is not tuned until the thread is started.

After executing the main method, the console prints as follows:

MyThread 的线程对象正在执行任务MyThread 的线程对象 10MyThread 的线程对象正在执行任务MyThread 的线程对象 11MyThread 的线程对象正在执行任务MyThread 的线程对象 12MyThread 的线程对象正在执行任务MyThread 的线程对象 13MyThread 的线程对象正在执行任务MyThread 的线程对象 14MyThread 的线程对象正在执行任务MyThread 的线程对象 15MyThread 的线程对象正在执行任务MyThread 的线程对象 16MyThread 的线程对象正在执行任务MyThread 的线程对象 17MyThread 的线程对象正在执行任务MyThread 的线程对象 18MyThread 的线程对象正在执行任务MyThread 的线程对象 19

As can be seen, the thread ID is a thread-unique identifier, and each thread ID is not the same.

Relationship between the Start method and the Run method:

Similarly, implementing the Runnable interface class to create thread objects is also simple, just a different form. The new Mythreadbrother code is as follows:

/*** Implement Runnable interface class to create thread object * @authorJeff Lee @ bysocket.com * @sinceJanuary 27, 2018 21:22:57 */ Public classMythreadbrotherImplementsRunnable {@Override //Can be omitted     Public void Run() {System. out.println("Mythreadbrother thread object is performing a task"); } Public Static void Main(string[] args) { for(inti =0; I <Ten; i++) {Thread thread =NewThread (New Mythreadbrother()); Thread.Start(); System. out.println("Mythreadbrother Thread Object"+ Thread.getId()); }    }}

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

2.1 Running a thread

After running the two small demos, the JVM executes the main function thread and then executes the new thread in the main thread. Normally, all threads are executed until the end of the run. Unless System.exit (1) is called in a thread, it is terminated.

In real-world development, a request-to-response is a thread. In this thread, however, a new thread can be created by using thread pool to perform the task.

3 Status of the thread

To create a new Mythreadinfo class, Print thread object properties with the following code:

/*** attribute values for thread instance objects * @authorJeff Lee @ bysocket.com * @sinceJanuary 27, 2018 21:24:40 */ Public classMythreadinfoextendsThread {@Override //Can be omitted     Public void Run() {System. out.println("Mythreadinfo thread instance is performing a task");//System.exit (1);} Public Static void Main(string[] args) {Mythreadinfo thread =New Mythreadinfo(); Thread.Start(); System. out.Print(the thread object for the Mythreadinfo\ n"+"thread Unique identifier:"+ Thread.getId() +"\ n"+"Thread Name:"+ Thread.GetName() +"\ n"+"thread state:"+ Thread.getState() +"\ n"+"Thread Priority:"+ Thread.getpriority()); }}

The execution code prints as follows:

MyThreadInfo 的线程实例正在执行任务MyThreadInfo 的线程对象 线程唯一标识符:10线程名称:Thread-0线程状态:NEW线程优先级:5

A thread is an object that has a unique identifier ID, name, status, priority, and so on. A thread can only modify properties such as its priority and name, and cannot modify the ID or state. The ID is assigned by the JVM, and the default name is Thread-xx,xx is a set of numbers. The initial state of the thread is NEW.

The thread priority range is 1 to 10, where 1 is the lowest priority and 10 is the highest priority. Changing the priority of a thread is not recommended, and if the business requires it, it can naturally modify the thread priority to the highest, or lowest.

The state implementation of the thread is implemented by the Thread.state constant class, with 6 thread states: New (new), runnnable (operational), blocked (blocking), Waiting (wait), time waiting (timed wait), and Terminated (termination). The status transition diagram is as follows:

The thread state flow is roughly as follows:

    • After the thread is created, enter the new state
    • Call the start or Run method to enter the runnable state
    • The JVM performs runnable-state threads, such as thread priority and time fragmentation. Enter running state when starting execution
    • If the thread performs sleep, wait, join, or enter IO blocking, and so on. Enter wait or blocked status
    • When the thread finishes executing, the thread is removed by the thread queue. Finally, the terminated state.
4 Summary

This article introduces the basic thread and multithreading, including thread initiation and thread state. Next we talk about the specific operation of the thread. Including interrupts, terminations, etc.

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

Reference:
The art of Java concurrent programming
Java 7 Concurrent Programming Practical manual
Graphical Java multithreaded design pattern

Mason Chat Concurrent Programming: Threads and multithreading must Know (Basic)

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.