Basic Concepts of threading

Source: Internet
Author: User
Tags abstract thread class visibility cpu usage

According to the plan, from the beginning of this chapter we open the "concurrent" series of content summary, from the thread of this article, to the thread pool, to the analysis of several concurrent collection source code, we come a little, hope you also have patience, because this piece of knowledge is your career always around the threshold, Any project is more or less involved in a number of concurrent processing.

This series of articles can only be regarded as a summary and introduction of the basic theoretical knowledge of concurrency, want to become a master of concurrency, it is necessary to pass large-scale concurrent access to the online scene application, perhaps I have relevant experience, and then give you to do a bit of sharing it.

Basic Process Threading Concepts

Process and thread are two very basic and important concepts in the operating system, the process is the basic unit of protection and resource allocation in the operating system, and the operating system allocates resources to process as the basic unit. threads, which are part of a process, represent a sequential flow of execution.

The process threading model in the system is this:

The process obtains basic memory space from the operating system, and all threads share the memory address space of the process. Of course, each thread will also have its own private memory address range that other threads cannot access.

Because all threads share the memory address space of the process, the communication between threads is much easier and can be achieved by sharing process-level global variables.

At the same time, before the introduction of multithreading concept, so-called "concurrency" occurs between processes, each time the process context switch will lead to the operation of the system scheduling algorithm, as well as the various CPU context information preservation, very time-consuming. While thread-level concurrency does not have a system scheduling step, the process is allocated to CPU usage time and is used by various threads within it.

In a timeshare system, each thread in the process has a time slice, saves the thread context in the CPU and register at the end of the time slice, and hand over the CPU to complete a thread switch. Of course, when the CPU time of the process ends, all threads must be blocked.

JAVA Abstraction of Threading concepts

The JAVA API uses the thread class to abstract the thread, which has several states:

    • NEW: Line Cheng Gang is created
    • RUNNABLE: Thread is in executable state
    • BLOCKED, waiting: Threads are blocked, specific differences say
    • TERMINATED: Thread execution ended, terminated

Where RUNNABLE represents the thread executable, but does not mean that the thread must be getting CPU execution, it may wait for the system to be re-dispatched due to the end of the time slice usage. BLOCKED, waiting are temporarily blocked due to the lack of certain conditions during thread execution, and once they wait for the condition to meet, they will return to the RUNNABLE state to re-compete with the CPU.

In addition, some properties in the thread class are used to describe a thread object:

    • Private long TID: serial number of the thread
    • Private volatile char name[]: Name of the thread
    • private int Priority: Thread precedence
    • Private Boolean daemon = false: Whether it is a daemon thread
    • Private Runnable Target: The method that the thread needs to execute

Where Tid is a self-increment field, and each new thread is created, the ID is added from one to another. The priority value range, from one to 10, the greater the value, the higher the priority, the default value is five.

Runnable is an interface that abstracts the execution flow of a thread, defined as follows:

public interface Runnable {    public abstract void run();}

By overriding the Run method, you also indicate the starting point for your thread to execute instructions after getting the CPU. We usually pass this parameter when we construct the Thread instance.

Create and start a thread

There are basically two ways to create a thread, one is to pass in the Runnable implementation class, and the other is to rewrite the thread class's Run method directly. Let's take a closer look:

1. Custom Runnable Implementation

public class MyThread implements Runnable{    @Override    public void run(){        System.out.println("hello world");    }}
public static void main(String[] args) {    Thread thread = new Thread(new MyThread());    thread.start();    System.out.println("i am main Thread");}

Operation Result:

i am main Threadhello world

In fact the Thread this class also inherits the Runnable interface, and provides the default Run method implementation:

@Overridepublic void run() {    if (target != null) {       target.run();    }}

Target we said, it's a field of type Runnable, and the Thread constructor initializes the target field. So when the thread starts, the run method that is called is the Run method of the implementation class that we implement.

So, naturally there is a second way to create it.

2. Inherit the Thread class

Now that the thread starts to call the Run method, we can simply rewrite the thread class's Run method to define our threading class.

public class MyThreadT extends Thread{    @Override    public void run(){        System.out.println("hello world");    }}
Thread thread = new MyThreadT();thread.start();

The effect is the same.

A few common methods

With regard to threading operations, the thread class also gives us some methods, some of which are more commonly used.

1. Sleep

public static native void sleep(long millis)

This is a local method that blocks the current thread for the specified millisecond length.

2. Start

public synchronized void start()

This method may be a lot of people wonder why I have to rewrite the Runnable run method to specify the work of the thread, but it is through the Start method to start the thread?

That's because starting a thread is more than just giving a command to start the portal, and the operating system needs to partition a portion of the process's shared memory space as a private resource for the thread, create a program counter, stack, and so on, and eventually call the Run method.

3, interrupt

public void interrupt()

This method is used to interrupt the current thread, and of course the different states of the thread should be different in how the interrupts are broken, which we'll say later.

4. Join

public final synchronized void join(long millis)

This method is typically called in other threads, indicating that the current thread needs to be blocked at the current location, waiting for all instructions from the target thread to complete. For example:

Thread thread = new MyThreadT();thread.start();thread.join();System.out.println("i am the main thread");

Normally, the print statement of the main function executes before the Mythreadt thread run method executes, and the join statement indicates that the main thread must block until the Mythreadt execution finishes.

Some problems caused by multithreading

The advantages of multithreading we do not say, now look at multi-threading, that is, what memory problems will be in the concurrency.

1. Race conditions

This is a problem that when multiple threads access and modify the same object at the same time, the object's final value is often less than expected. For example:

We created 100 threads, each starting with a random sleep, and then adding one to count, and executing the flow in a general order, the value of Count would be 100.

But I tell you, no matter how many times you run, the results are different, and the probability of 100 is very low. This is concurrency, the reason is very simple, count++ this operation it is not a directive can do.

It is divided into three steps, reading the value of count, increment one, and write back the variable count . Multithreading does not know each other, are performing these three steps, so a thread is currently reading the data value may not be up to date, the result is not as expected.

However, this is concurrency.

2. Memory visibility

Memory visibility means that, in some cases, changes to some resource variables are not immediately flushed into memory by the thread, but are temporarily stored in the cache and register.

The most straightforward problem with this is that the modification of the shared variable is not visible to the other thread.

This code is very simple, the main thread and our threadtwo share a global variable flag, which has been monitoring the change in the value of the variable, and we modify the value of this variable in the main thread, due to memory visibility problems, the main thread changes are not immediately mapped to memory, There is a temporary cache or register, which causes the threadtwo not to know the change of the flag value and has been doing the loop.

To summarize, a process acts as a basic unit for allocating resources to a system, while threads are part of a process, sharing resources in a process, and a thread is the smallest execution flow of a system schedule. In real-time systems, each thread obtains a time slice call CPU, multi-threaded concurrent use CPU, each context switch corresponds to "Run the scene" save and restore, this is also a relatively time-consuming operation.

PS: The previous period is indeed a bit busy, drag better days, here again to say sorry, thank you haven't gone, now formally restored, open the Concurrency series summary ~

All the code, pictures, and files in the article are stored on my GitHub:

(Github.com/singleyam/overview_java)

Welcome to the public number: Onejavacoder, all articles will be synchronized to the public number.

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.