Analyzing the concept of Java thread programming _java

Source: Internet
Author: User
Tags thread class

The concept of Java threads
Unlike most other computer languages, Java built-in support for multithreaded programming (multithreaded programming).

A multithreaded program contains two or more concurrent runs of more than two pieces. Each such part of the program is called a thread (thread), and each thread has a separate execution path. Therefore, multithreading is a special form of multitasking.

You must know multitasking because it's actually supported by all modern operating systems. However, multitasking has two distinct types: process-based and thread-based. It is very important to know the difference between the two.

For many readers, process-based multitasking is a more familiar form. A process is essentially a program that executes. Therefore, the feature of process based multitasking (process-based) is to allow your computer to run two or more programs at the same time. For example, process-based multitasking enables you to run the Java compiler at the same time using a text editor. In process-based multitasking, a program is the smallest unit of code assigned by the scheduler.

In a multithreaded (thread-based) multitasking environment, threads are the smallest unit of execution. This means that a program can perform the functions of two or more tasks at the same time. For example, a text editor can format text while printing. Therefore, the multi-process program handles the "big picture", while multithreaded programs handle the details.

multithreaded programs require less overhead than a multiple-process program. Processes are heavyweight tasks that need to be assigned their own independent address space. Interprocess communication is expensive and limited. Conversion between processes is also costly. On the other hand, threads are lightweight players. They share the same address space and share the same process together. The communication between threads is cheap, and the conversion between threads is also low cost. When a Java program uses a multitasking task to process the environment, the multi-process program is not controlled by Java, while multithreading is controlled by Java.

Multithreading helps you write efficient programs that maximize CPU utilization, because idle time is kept to a minimum. This is critical to the interactive network interconnect environment that Java is running in, because idle time is public. For example, the network data transmission rate is far lower than the computer processing power, the local file system resources read and write speed is much lower than the CPU processing power, of course, user input is much slower than the computer. In a traditional single-threaded environment, your program must wait for each such task to complete before performing the next step-although the CPU has a lot of free time. Multithreading allows you to get and make the most of your free time.

Java Threading Model
The Java running system relies on threads in many ways, and all class library designs take multithreading into account. In fact, Java uses threads to make the entire environment asynchronous. This helps to reduce the number of invalid parts by preventing waste from CPU cycles.

To better understand the advantages of a multithreaded environment, it can be compared with its control. Single-threaded systems are handled using an event-looping method called polling. In this model, single-threaded control runs in an infinite loop, polling an event sequence to determine what to do next. Once the polling device return signal indicates that the network file is ready to be read, event loop Scheduling control is administered to the appropriate event handler. No other events occur in the system until the event handler returns. This is a waste of CPU time. This results in a part of the program monopolizing the system and preventing the execution of other events. In general, single-threaded environments, when a thread blocks (block, suspend execution) because it waits for resources, the entire program stops running.

The advantage of Java multithreading is that it cancels the main cycle/polling mechanism. A thread can be paused without affecting other parts of the program. For example, the idle time that occurs when a thread reads data from the network or waits for user input can be exploited elsewhere. Multithreading allows a live loop to sleep one second in each frame gap without pausing the entire system. There is a thread blocking in the Java program, and only one thread is paused and the other threads continue to run.

Threads exist in several different states. The thread can be running (running). It can run as long as the CPU time is obtained. The running thread can be suspended (suspend) and temporarily interrupt its execution. A suspended thread can be restored (resume, allowing it to continue running from where it stopped.) A thread can be blocked (block) while waiting for a resource.

At any time, the thread can terminate (terminate), which immediately interrupts its operation. Once terminated, the thread cannot be recovered.
Thread Priority

Java prioritizes each thread to determine how to treat the thread when compared to other threads. Thread precedence is an integer that details the precedence relationship between threads. As an absolute value, precedence is meaningless; when there is only one thread, a higher priority thread does not run faster than a thread with a lower priority. Instead, the thread priority is used to decide when to switch from one running thread to another. This is called context switch. The rules that determine the occurrence of context conversions are simple:
Threads can automatically discard control. In the case where I/O is not determined, sleep or congestion is accomplished by a definite concession. Under this assumption, all other threads are instrumented, and the highest priority thread ready to run is granted to the CPU.
Threads can be preempted by higher-priority threads. In this case, the low-priority thread does not voluntarily discard, the processor is only first accounted for-whatever it is doing-the processor is occupied by high-priority threads. Basically, once a high priority thread is to run, it executes. This is called multitasking with priority.

The situation is a bit more complicated when two of the same priority threads compete for CPU cycles. For an operating system such as WINDOWS98, the thread of equal priority is automatically dividing the time in the loop mode. For other operating systems, such as the Solaris 2.x, the priority line threads relative is automatically discarded for their peers. If this is not the case, the other threads will not run.

Warning: Context conversions for priority threads on different operating systems may cause errors.
Sync Sex

Because multithreading introduces an asynchronous behavior in your program, you must have a way to enhance synchronization when you need it. For example, if you want two threads to communicate with each other and share a complex data structure, such as a list sequence, you need some way to make sure that they don't conflict with each other. That is, you have to prevent one thread from writing the data and another thread is reading the data in the list. To this end, Java has implemented an alternative approach based on the old pattern of interprocess synchronization: Enhancement (monitor). Enhancement is a control mechanism defined first by C.a.r.hoare.

You can think of the process as a small box that controls only one thread. Once the thread has entered the pipe, all threads must wait until the thread exits the pipe. In this way, a pipe can be used to prevent shared resources from being manipulated by multiple threads.

Many multithreaded systems take the process as an object that must be explicitly referenced and manipulated by the program. Java provides a clear solution. There is no "Monitor" class; instead, each object has its own implicit pipe, which is automatically loaded when the object's synchronization method is invoked. Once a thread is contained in a synchronization method, no other thread can invoke the synchronization method of the same object. This allows you to write very clear and concise multithreaded code, because synchronization support is built into the language.
Message delivery

After you divide the program into threads, you define the links between the threads. When planning in most other languages, you must rely on the operating system to establish communication between threads. This, of course, increases the cost. However, Java provides a clean, low-cost way to talk between multithreading-by invoking predetermined methods for all objects. The Java messaging system allows a thread to enter a synchronized method of an object, and then wait there until the other thread explicitly notifies it out.
Thread class and Runnable interface

Java's multithreaded system is based on the thread class, its method, its common interface runnable. The thread class encapsulates the execution of threads. Since you cannot directly reference the state of a running thread, you have to handle it through its proxy, so the thread instance is generated. To create a new thread, your program must extend the thread or implement the Runnable interface.

The thread class defines several ways to help manage threads. The methods used in this chapter are as shown in the table:

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.