Java Multithreading Technology

Source: Internet
Author: User
Tags dashed line cpu usage

Multi-threaded programming has always been a headache and a guilty place, because the thread execution sequence of unpredictable and debugging difficulties, so many people in the face of multi-threaded situations to choose to escape, the use of single-threaded way, in fact, as long as we have a clear understanding of the thread, coupled with the Java built-in support for multithreading natural , multithreaded programming is no longer an insurmountable chasm.

process, thread, concurrent execution

First, let's take a look at the concepts of process, thread, concurrency execution:

In general, when you run an application, you start a process, and some of course start multiple processes. When the process is started, the operating system allocates resources to the process, the most important of which is memory space, because the program runs in memory.

In the process, some program flow blocks can be executed in a random order, and the code block can be executed multiple times at the same time. In fact, such blocks of code are thread bodies. A thread is a code flow that is executed in a process in a disorderly order. This execution pattern becomes concurrent execution when multiple threads are running concurrently.

Here I use a simple example of everyday life to illustrate the differences and linkages between processes and threads:

This diagram is a two-way multi-lane road map, and if we look at the whole road as a "process", then each lane separated by a white dashed line in the figure is the "thread" in the process.

    1. These threads (lanes) share common resources (land resources) for processes (roads).
    2. These threads (lanes) must be dependent on the process (road), that is, the thread cannot be separated from the process (as if it were out of the way, the lane would be meaningless).
    3. These threads (lanes) can be executed concurrently (each lane you walk, I walk my), or you can sync with each other (some lanes are forbidden to move on or turn when the traffic lights are on, and must wait for the other lanes to pass).
    4. These threads (lanes) rely on code logic (traffic lights) to control the operation, and once the code logic is incorrectly controlled (deadlock, multiple threads compete for the only resource at the same time), then the thread will fall into chaos and disorder.
    5. These threads (lanes) between who run first is unknown, only the moment the thread is assigned to the CPU time slice (traffic light change) can be known.
JVM and multithreading

Java-written programs are run in a Java Virtual machine (JVM), and within the JVM, the program's multitasking is done through threads.

Starting a Java application with Java commands starts a JVM process. In the same JVM process, there is only one process, which is itself. In this JVM environment, all program code runs as threads. The JVM finds the entry point of the program, Main (), and then runs the main () method, which creates a thread called the main thread. When the main method finishes, the main thread runs. The JVM process also exits.

The operating system manages the process threads, and in turn (without a fixed order) allocates a short period of time for each process (not necessarily evenly distributed), and then within each process, the program code processes the internal threads of the process itself, switching between threads to execute, and the switching time is very short.

Support for multithreading in the Java language

The Java language support for multithreading is implemented through the class thread and interface runnable. There's not much to say here. Here the emphasis is placed on two places:

Main thread other code snippet
ThreadClass subthread = new ThreadClass ();
Subthread.start ();
Main thread other code snippet
Subthread.sleep (1000);

Some people think that after calling the start () method, the following code must start the child thread first and then the main thread will continue to execute. The CPU does nothing after calling the sleep () method, where it waits for the time to hibernate to end. In fact, this understanding is wrong. Because:

    1. The start () method does not execute multithreaded code immediately after it is called, but instead makes the thread operational (Runnable), and when it is run is determined by the operating system.
    2. The purpose of the Thread.Sleep () method call is to not allow the current thread to occupy the CPU resources acquired by the process on its own, in order to allow a certain amount of time for other threads to execute (that is, by internal coordination).
State switching of threads

As we mentioned earlier, because when the thread is executed is unknown, the thread can actually execute only if the CPU is assigned to a time slice. The process of thread execution may be suspended for a variety of reasons (as in the previous example: Cars can travel only when the traffic lights turn green, and there may be traffic jams, waiting for other vehicles to pass or turn in the process).

This way the thread has the concept of "state", and the following diagram is a good reflection of the state change of the thread under different circumstances.

    • New state: A new Thread object was created.
    • Ready state (Runnable): After the thread object is created, other threads call the object's start () method. The state of the thread is located in a pool of running threads that becomes operational and waits for the CPU to be used.
    • Running state (Running): The ready state of the thread gets the CPU and executes the program code.
    • Blocking state (Blocked): The blocking state is a temporary stop when the thread abandons the CPU usage for some reason. Until the thread is in a ready state, the opportunity to go to the running state is reached. There are three types of blocking:
      1. Wait for blocking: The running thread executes the wait () method, and the JVM puts the thread into the waiting pool.
      2. Synchronous blocking: When a running thread acquires a synchronization lock on an object, the JVM puts the thread into a lock if the synchronization lock is occupied by another thread.
      3. Other blocking: The running thread executes the sleep () or join () method, or when an I/O request is made, the JVM will place the thread in a blocked state. When the sleep () state times out, join () waits for the thread to terminate or time out, or the I/O process finishes, the thread is re-entered in a ready state.
    • Dead State (Dead): The thread finishes executing or exits the run () method because of an exception, and the thread ends the life cycle.
Scheduling API for Threads in Java

The following are some of the most important APIs for thread scheduling in Java:

    1. Thread sleep: thread.sleep (Long Millis) method
    2. Thread waits: The Wait () method in the object class
    3. Thread Concession: Thread.yield () method
    4. Thread join: Join () method
    5. Thread Wakeup: The Notify () method in the object class

For a detailed application of these methods, you can refer to the Sun API. Here I focus on the differences and use of these methods.

The difference between the sleep method and the Wait method:

    1. The sleep method is a static method, and the wait method is a non-static method.
    2. The sleep method wakes itself up after the time, but wait cannot, and the other thread must let it "wake up" by the Notify (all) method.
    3. The sleep method is typically used in cases where there is no need to wait for resources, such as waiting for threads, database connections, and wait.

Sleep/wait differs from the Yeld method: After the sleep or wait method is called, the thread enters the block state, and the thread enters the runnable state after the Yeld method is called.

The difference between the wait and join methods:

    1. The wait method represents a mutually exclusive relationship between threads, and the Join method represents the synchronization relationship between threads.
    2. The wait method must be unlocked by another thread, and the join method does not require that the current thread automatically become ready as long as the waiting thread finishes executing.
    3. One purpose of the Join method is to have the thread wait until all the child threads have finished executing the business logic before the child threads are done.

Through the above introduction, I believe the students have a basic understanding and understanding of the multithreading in Java. In fact, multithreaded programming is not so difficult for everyone to imagine, as long as in the actual study, work constantly practice and use, I believe you will soon be able to master the mystery, and thus write a pleasing Java program.

Turn http://express.ruanko.com/ruanko-express_6/webpage/tech4.html

Java Multithreading Technology

Related Article

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.