Java thread Introduction to Java multithreaded programming _java

Source: Internet
Author: User
Tags thread class

First, thread overview

A thread is the basic execution unit of a program's operation. When the operating system (excluding single-threaded operating systems, such as Microsoft's early Dos) executes a program, a process is established in the system, and in this process, at least one thread (which is called the main thread) must be established as the entry point for the program to run. Therefore, any program running in the operating system has at least one main thread.
Processes and threads are two essential operational models in modern operating systems. There can be multiple processes in the operating system, including systems processes (processes established within the operating system) and user processes (processes established by user programs), and one or more threads in a process. No memory is shared between processes and processes, which means that processes in the system run in their own separate memory space. A line in a process can share the memory space that the system assigns to the process.
The thread can not only share the memory of the process, but also have a memory space of its own, which is also called the line stacks, which is allocated by the system when the thread is established, and is used primarily to hold the data used within the thread, such as the variables defined in the thread execution function.
Note: Whenever a thread is established, it executes a function called the thread execution function. You can also consider this function as the entry point of a thread (similar to the main function in a program). No matter what language or technology you use to build a thread, you must perform this function (the function may behave differently, but there will be one). The third parameter of the API function CreateThread, which is used to create threads in Windows, is the pointer to this execution function.
After the operating system divides processes into multiple threads, these threads can be executed concurrently under the management of the operating system, thus greatly increasing the efficiency of the program. Although the execution of a thread is macroscopic, multiple threads execute simultaneously, but in reality this is just the camouflage of the operating system. Because a CPU can only execute one instruction at a time, it is not possible to perform two tasks simultaneously on a computer that has a single CPU. The operating system, in order to improve the efficiency of the program, when a thread is idle will remove the thread, and will let other threads to execute, this way is called thread scheduling. The reason we look at it on the surface is that multiple threads are executing at the same time because of the very short transitions between different threads and, in general, switching very frequently. Let's say we wired A and B. At run time, it may be 1 milliseconds after a execution, and after switching to B, B performs another 1 milliseconds, then switches to a,a and executes 1 milliseconds. Since the 1 millisecond time is difficult for the average person to perceive, it looks like A and b at the same time from the surface, but actually a and B are alternately executed.

Second, the advantages that the thread brings to us

Using threads properly can reduce development and maintenance costs and even improve the performance of complex applications. As in GUI applications, it is also better to handle events through the asynchronous nature of threads; In Application server programs, you can create multiple threads to handle requests from clients. Threads can even simplify the implementation of virtual machines, such as the Java Virtual Machine (JVM) garbage collector (garbage collector), which typically runs on one or more threads. Therefore, using threads will improve our applications in the following five ways:

1. Make full use of CPU resources
Most computers in the world now have only one CPU. Therefore, the full use of CPU resources is particularly important. When a single-threaded program is executed, the CPU may be idle due to a blocking process. This will result in a lot of waste of computational resources. Using multithreading in your program allows you to run other threads when a thread is dormant or blocked, and the CPU is in a state of idle. So the CPU is very difficult to have idle time. As a result, CPU resources are fully utilized.

2. Simplified programming model
If the program completes only one task, write a single single-threaded program and write the code as you follow the steps to perform the task. But to accomplish a number of tasks, if you are using a single thread, you have to determine in your program whether each task should be executed and when. such as the time, minute, and second three pointers for displaying a clock. Using a single thread, you have to determine the rotation time and angle of the three pointers in the loop. If you use three threads to separate the display of these three pointers, then for each thread it means a separate task. This helps developers understand and maintain the program.

3. Simplifies processing of asynchronous events
The easiest way to handle a server application when it receives a different client connection is to create a thread for each client connection. The listening thread is then still responsible for listening for requests from the client. If the application is single-threaded, when a listener thread receives a client request and begins to read data from the client, the Read method is blocked after reading the data, which means that the thread will no longer be able to listen for client requests. To handle multiple client requests in a single thread, you must use non-blocking socket connections and asynchronous I/O. However, using asynchronous I/O is more difficult to control than using synchronous I/O and is more prone to error. Therefore, using multithreading and synchronous I/O makes it easier to handle asynchronous events that are similar to multiple requests.

4. Make GUI more efficient
When using a single thread to handle GUI events, you must use loops to scan for possible GUI events, in addition to scanning GUI events inside the loop, to execute other program code. If the code is too long, the GUI events are "Frozen" until the code is executed.
GUI events are scanned in modern GUI frameworks such as swing, AWT, and SWT using a separate event dispatch thread (the event dispatch Thread,edt). When we press a button, the button's Click event function is invoked in this event dispatch thread. Because the task of EDT is only to scan GUI events, this approach is very quick to react to events.

5.   cost savings
Improve program execution generally there are three ways to do this:
(1) Increase the number of CPUs on your computer.
(2) Start multiple processes for a program
(3) Use multiple processes in your program.
The first method is the easiest, but also the most expensive. This method does not need to modify the program, theoretically, any program can use this method to improve execution efficiency. The second approach is not easy to share without having to buy new hardware, but it is not convenient if the task that the program is to complete needs to share data, and starting multiple threads consumes a lot of system resources. The third approach compensates for the drawbacks of the first method and inherits their advantages. That is, neither need to buy the CPU, nor does it consume large amounts of system resources because of too many threads (by default, a thread takes up much less memory space than a process), and multithreading can simulate how multiple CPUs are run, so Using multithreading is the cheapest way to improve program execution efficiency.

Third, Java threading Model
because Java is a pure object-oriented language, the Java threading model is also object-oriented. Java encapsulates the functionality required by a thread through the thread class. To create a thread, you must have a thread that executes the function, which executes the function corresponding to the thread class's Run method. The thread class also has a start method that is responsible for establishing the thread, which is equivalent to calling the build thread function CreateThread of Windows. When the Start method is called, the thread class's Run method is automatically invoked if it is established successfully. Therefore, any Java class that inherits thread can establish a thread through the start method of the thread class. If you want to run your own thread execution function, you must overwrite the thread class's Run method.
In addition to the thread class in the Java threading model, there is also an interface runnable that identifies whether a Java class can be a thread class, and this interface has only one abstract method run, which is the thread execution function of the Java threading model. Therefore, the only criterion for a thread class is whether the class implements the Run method of the Runnable interface, that is, the class that owns the thread execution function is the thread class.
As you can see from the above, there are two ways to build a thread in Java, one is to inherit the thread class, the other is to implement the Runnable interface and create threads through thread and implementation of runnable classes, which are essentially a method, That is, the thread class is used to create threads and runs the Run method. But the big difference is that by inheriting the thread class to build threads, although it is easier to implement, because Java does not support multiple inheritance, the thread class cannot inherit other classes if it inherits thread. The Java threading model provides a way to create threads by implementing the Runnable interface, so that the thread class can inherit the business-related classes, rather than the thread class, when necessary.

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.