The concept of Java threading <br /> Unlike most other computer languages, Java supports multithreaded programming in built-in.
A multi-threaded program contains two or more parts that run concurrently. Each such part in the program is called a thread, and each thread has an independent execution path. Therefore, multithreading is a special form of multitasking.
You must know multitasking because it is actually supported by all modern operating systems. However, there are two distinct types of multitasking: process-based and thread-based. It is very important to understand the differences between the two.
For many readers, process-based multitasking is a more familiar form. A process is essentially an executing program. Therefore, process-based multitasking is characterized by allowing your computer to run two or more programs simultaneously. For example, process-based multitasking allows you to run the Java compiler simultaneously while using a text editor. In process-based multitasking, a program is the smallest unit of code assigned by the scheduler.
In a thread-based multitasking environment, threads are the smallest execution unit. This means that a program can perform functions of two or more tasks simultaneously. For example, a text editor can format text while printing. Therefore, multi-process programs handle "big pictures", while multi-threaded programs handle details.
Multithreaded programs require less administrative expenses than multi-process programs. Processes are heavyweight tasks that require their own independent address space. Inter-process communication is expensive and restricted. Transformation between processes is also very costly. Threads, on the other hand, are lightweight players. They share the same address space and share the same process together. Inter-thread communication is cheap, and inter-thread conversion is also low-cost. When a Java program uses a multi-process task processing environment, the multi-process program is not controlled by Java, while multi-threading is controlled by Java.
Multithreading helps you write efficient programs with maximum CPU utilization, as idle time is kept to a minimum. This is crucial for interactive network interconnect environments running in Java, because free time is public. For example, the network's data transmission rate is much lower than the computer's processing capacity, and the reading and writing speed of local file system resources is much lower than that of the CPU. Of course, user input is much slower than that of 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 this free time.
Java threading model
The Java runtime system relies on threads in many ways, and all class library designs take into account multithreading. In fact, Java uses threads to make the entire environment asynchronous. This helps reduce the invalid part by preventing the waste of CPU loops.
To better understand the advantages of a multithreaded environment, it can be compared with its controls. The processing method of a single-threaded system is to use an event loop method called polling. In this model, single-threaded control runs in an infinite loop, polling a sequence of events to determine what to do next. Once the polling device returns a signal that the network file is ready to be read, the event loop scheduling control manages to the appropriate event handler. Until the event handler returns, no other events occur in the system. This wastes CPU time. This causes part of the program to occupy the system exclusively and prevent the execution of other events. In general, in a single-threaded environment, when a thread blocks (blocks, suspends execution) while waiting for resources, the entire program stops running.
The advantage of Java multithreading is that it cancels the main loop/polling mechanism. A thread can be paused without affecting other parts of the program. For example, the idle time generated when a thread reads data from the network or waits for user input can be utilized elsewhere. Multithreading allows a live loop to sleep for one second in each frame gap without pausing the entire system. There is a thread blockage in a Java program, only one thread is suspended, and the other threads continue to run.
Threads exist in several states. The thread can be running. It can run as long as you get CPU time. The running thread can be suspended and temporarily interrupt its execution. A suspended thread can be resumed, allowing it to continue running from where it stopped. A thread can be blocked while waiting for a resource.
At any time, the thread can terminate, which immediately interrupts its operation. Once terminated, the thread cannot be restored.
Thread priority
Java prioritizes each thread to determine how to treat the thread when compared with other threads. Thread priority is an integer that details the priority relationship between threads. As an absolute value, priority is meaningless; when there is only one thread, the thread with high priority does not run faster than the thread with low priority. Instead, thread priority is used to determine when to switch from one running thread to another. This is called "context switch". The rules that determine the occurrence of context conversion are simple:
Threads can automatically give up control. In the case of I/O undecided, sleep or blocking is done by explicit concessions. Under this assumption, all other threads are detected and the highest priority thread ready to run is granted to the CPU.
Threads can be preempted by high-priority threads. In this case, the low-priority thread does not give up actively, the processor is just occupied first - no matter what it is doing - the processor is occupied by the high-priority thread. Basically, once a high priority thread is about to run, it executes. This is called priority multitasking.
The situation is a little complicated when two threads of the same priority compete for CPU cycles. For operating systems like Windows 98, threads with equal priority automatically divide time in loop mode. For other operating systems, such as Solaris 2.x, priority threads are automatically abandoned relative to their peers. If this is not the case, other threads will not run.
Warning: Context conversion of lower priority threads on different operating systems may generate errors.
Synchronization
Because multithreading introduces an asynchronous behavior in your program, there must be ways 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 sequence of linked lists, you need some way to make sure they are not conflicting with each other. That is, you have to prevent one thread from writing data while another thread is reading data from the linked list. To this end, Java implements another method based on the old model of inter-process synchronization: monitor. The management process is a control mechanism first defined by CARHoare.
You can think of the management process as a small box that controls only one thread. Once a thread enters a pipe, all threads must wait until the thread exits the pipe. In this way, the management can be used to prevent shared resources from being manipulated by multiple threads.
Many multi-threaded systems regard the management process as an object that the program must clearly refer to and operate. Java provides a clear solution. There is no "Monitor" class; instead, each object has its own implicit manipulation, which is automatically loaded when the object's synchronization method is called. Once a thread is included in a synchronization method, no other thread can call the synchronization method of the same object. This allows you to write very clear and concise multi-threaded code, as synchronization support is built-in to the language.
Message delivery
After you divide the program into several threads, you need to define the connection between each thread. When planning in most other languages, you have to rely on the operating system to establish inter-thread communication. This will certainly increase the cost. However, Java provides a clean, low-cost way to talk between multithreads - by calling predefined methods that all objects have. Java's messaging system allows a thread to enter a synchronous method of an object and then wait there until other threads explicitly notify it out.
Thread class and Runnable interface
Java's multi-threaded system is based on the Thread class, its methods, and its co-company interface Runnable. The Thread class encapsulates the execution of threads. Since you cannot directly refer to the state of the running thread, you have to process it through its proxy, so the Thread instance is generated. To create a new thread, your program must extend Thread or implement the Runnable interface.
The Thread class defines several methods to help manage threads. The methods used in this chapter are shown in the table: