JAVA thread concepts

Source: Internet
Author: User

JAVA thread concepts
Unlike most other computer languages, Java supports multithreaded programming ).

A multi-threaded program contains two or more concurrent operations. Every such part of the program is called a thread, and each thread has an independent execution path. Therefore, multithreading is a special form of multi-task processing.

You must be aware of multitasking because it is actually supported by all modern operating systems. However, there are two completely different types of multitasking: process-based and thread-based. It is very important to know the differences between the two.

For many readers, process-based multitasking is a more familiar form. A process is essentially an execution program. Therefore, process-based multitasking is characterized by allowing your computer to run two or more programs at the same time. For example, process-based multitasking enables you to run the Java compiler simultaneously when using a text editor. In process-based multi-task processing, a program is the smallest unit of code assigned by the scheduler.

In a thread-based multi-task processing environment, a thread is the smallest execution unit. This means that a program can execute two or more tasks at the same time. For example, a text editor can format text while printing. Therefore, multi-process programs process "Big images", while multi-threaded programs process details.

Multi-threaded programs require less management costs than multi-process programs. Processes are heavyweight tasks and need to be allocated their own independent address spaces. Inter-process communication is expensive and limited. Inter-process conversion is also very costly. On the other hand, threads 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 the multi-thread is controlled by Java.

Multithreading helps you write efficient programs with the maximum CPU utilization, because the idle time remains the lowest. This is vital for the Interactive Network Interconnection Environment running in Java, because the idle time is public. For example, the data transmission rate of the network is much lower than that of the computer, and the read/write speed of the 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 until such a task is completed before it can execute the next step-although the CPU has a lot of free time. Multithreading allows you to obtain and make full use of the free time.

If you have programming experience in Windows 98 or Windows 2000, you are familiar with multithreading. However, Java Management threads make multi-thread processing especially convenient, because many details are easy to process.
I. Concept of operating system midline process and Process
The current operating system is a multi-task operating system. Multithreading is a way to implement multiple tasks.
A process is an application running in the memory. Each process has its own memory space. A process can start multiple threads. For example, in Windows, a running exe is a process. A thread is an execution process in a process. A process can run multiple threads. For example, a java. EXE process can run multiple threads. A thread always belongs to a process. multiple threads in the process share the memory of the process. "At the same time" execution is a human perception, and is actually rotated between threads. Ii. threads in Java
In Java, "Thread" refers to two different things:
1. an instance of the java. lang. Thread class; 2. Thread execution. Use the java. lang. Thread class or java. lang. Runnable interface to write code to define, instantiate, and start a new Thread. A Thread class instance is just an object. Like any other object in Java, it has variables and methods, and is born and died on the heap. In Java, each thread has a call stack. Even if no new thread is created in the program, the thread runs in the background. A Java application always runs from the main () method, and the mian () method runs in a thread, which is called the main thread. Once a new thread is created, a new call stack is generated. Threads are divided into two types: User thread and waiting thread.
When all user threads are executed, the JVM automatically closes. However, the waiting thread is not independent from the JVM. The waiting thread is generally created by the operating system or the user.

1. Concepts of processes and threads

Process: A running application is called a process and has system resources (cpu and memory)

Thread: A piece of code in a process. A process can contain multiple sections of code. Does not own resources (share resources of the process)

In java, the program entry is automatically created as the main thread, and multiple subthreads can be created in the main thread.

Differences:

1. Resource occupation

2. The overhead required to create or cancel a process is greater than that required to create or cancel a thread.

3. The process is a heavyweight component and the thread is a lightweight component.

 

Multi-process: multiple tasks (programs) can be run simultaneously in the operating system)

Multithreading: multiple function streams are executed simultaneously in the same application.

 

2. Main Features of threads

① A file name cannot exist independently on the disk;

② It cannot be executed independently and can be started only after the process is started;

③ Threads can share the same memory (code and data) of processes ).

 

3. Main usage of threads

①. You can use it to complete repetitive work (such as playing an animation or sound ).

② Engage in one-time initialization (such as network connection and loading of sound data files ).

③ The Running Effect of concurrent execution (multiple threads in a process) to implement more complex functions

 

4. Main advantages of multi-threaded (multiple threads run simultaneously) Programs

① It can reduce the bottleneck of system performance, because it can be operated in parallel;

② Improve the efficiency of CPU processors. In multithreading, priority management can give priority to important programs and improve the flexibility of task management. On the other hand, in multiple CPU Systems, different threads can be executed in different CPUs to truly process multiple tasks at the same time.

Thread Overview (Introduction) a thread is the execution path of a program. The execution scheduling unit depends on the existence of the process. A thread not only shares the memory of a process, but also has its own memory space. This memory space is also called a thread stack, which is allocated by the system when a thread is created, it is mainly used to save the data used inside the thread, such as the variables defined in the thread execution function. Note: multithreading in Java is a preemption mechanism, not a time-sharing mechanism. The preemption mechanism means that multiple threads are running, but only one thread is allowed to run. They compete to seize the CPU.

What is multithreading?
In computer programming, a basic concept is to control multiple tasks at the same time. Many programming problems require the program to be able to stop the work at hand, to solve other problems, and then return to the main process. You can achieve this through multiple ways. At the beginning, programmers who master low-level machine languages wrote some "interrupt service routines", and the suspension of the main process was achieved through hardware-level interruptions. Although this is a useful method, the compilation of programs is difficult to transplant, resulting in another kind of high cost problem. Interruption is necessary for tasks with strong real-time performance. However, for many other problems, you only need to divide the problem into separate program fragments so that the entire program can respond to user requests more quickly. At the beginning, the thread is only a tool used to allocate the processing time of a single processor. However, if the operating system itself supports multiple processors, each thread can be allocated to a different processor, which truly enters the "Parallel Operation" state. From the perspective of programming languages, one of the most valuable features of Multithreading is that programmers do not have to worry about how many processors they actually use. The program is logically divided into several threads. If the machine itself is installed with multiple processors, the program runs faster without any special tuning. According to the previous discussion, we may feel that thread processing is very simple. But you must pay attention to one problem: sharing resources! If multiple threads run simultaneously and they attempt to access the same resource, a problem occurs. For example, two threads cannot send messages to a printer at the same time. To solve this problem, for shared resources (such as printers), they must be locked during use. Therefore, a thread can lock the resource and unlock (release) the lock after the task is completed, so that other threads can continue to use the same resource. Multithreading is used to synchronize multiple tasks, not to improve the running efficiency, but to improve the resource usage efficiency to improve the system efficiency. The thread is implemented when multiple tasks need to be completed at the same time. The simplest analogy is that multithreading is like every carriage of a train, and the process is a train. When a carriage leaves a train, it cannot run. Similarly, a train cannot only run one carriage. Multithreading is designed to improve efficiency. At the same time, it also brings about some problems.

Benefits of using threads

· Use threads to place tasks in programs that occupy a long time in the background for processing

· The user interface can be more attractive. For example, if a user clicks a button to trigger processing of some events, a progress bar will pop up to display the processing progress.

· Program running speed may be accelerated

· Threads are useful in the implementation of some waiting tasks, such as user input, file read/write, and network data sending and receiving. In this case, some precious resources such as memory usage can be released.

There are many other advantages of using multithreading, which are not described here.

Disadvantages of using threads

· If there are a large number of threads, performance will be affected because the operating system needs to switch between them.

· More threads require more memory space.

· The thread may bring more bugs to the program, so be careful when using it.

· The Impact of thread suspension on program running must be considered.

· Generally, block model data is shared among multiple threads, so it is necessary to prevent thread deadlocks.


Thread Overview (Introduction) a thread is the execution path of a program. The execution scheduling unit depends on the existence of the process. A thread not only shares the memory of a process, but also has its own memory space. This memory space is also called a thread stack, which is allocated by the system when a thread is created, it is mainly used to save the data used inside the thread, such as the variables defined in the thread execution function. Note: multithreading in Java is a preemption mechanism, not a time-sharing mechanism. The preemption mechanism means that multiple threads are running, but only one thread is allowed to run. They compete to seize the CPU. The definition of a Thread (Defining a Thread) has two methods. 1) inherits the java. lang. Thread class.
1.            /**  
2. * Create a Thread by inheriting the java. lang. Thread class
3.             *   
4.             * @author DreamSea 2011-12-29 20:17:06  
5.             */ 
6.            public class ThreadTest extends Thread {  
7.             
8.                /**  
9. * The JVM automatically calls the Override run () method.
10.             */ 
11.            public void run() {  
12.                System.out.println("I'm running!");  
13.            }  
14.        } 
Note: After the override run () method of the thread is called, JVM automatically calls the run method to execute the task, but overload run () method. This method is the same as a common member method and will not be automatically run by JVM because the start () method of the thread is called. For example:
1.            public class ThreadTest extends Thread {  
2.             
3.                /**  
4. * The JVM automatically calls the Override run () method.
5.                 */ 
6.                @Override 
7.                public void run() {  
8.                    System.out.println("I'm running!");  
9.                }  
10.         
11.            /**  
12. * The Overload run () method is the same as the normal method, and will not be automatically run by JVM after the start () method of the thread is called.
13.             */ 
14.            public void run(int times) {  
15.                System.out.println("I'm running!(Overload)");  
16.            }  
17.        } 
We do not recommend that you use this method to define threads, because after defining threads by inheriting threads, you cannot inherit other classes, resulting in greatly reduced program scalability. 2) Implement the java. lang. Runnable interface
1.            /**  
2. * Create a thread through the Runnable interface
3.             * @author DreamSea  
4.             */ 
5.            public class ThreadTest implements Runnable {  
6.                public void run() {  
7.                        System.out.println("I'm running!");  
8.                }  
9.            } 
A Thread must exist in a Thread class instance and start the Thread by calling the run () method. 1) if the Thread inherits the Thread class, the creation method is as follows:
1.            ThreadTest1 tt = new ThreadTest1();  
2.            tt.start(); 
2) If the Runnable interface is implemented, the creation method is as follows:
1.            ThreadTest2 tt = new ThreadTest2();  
2.            Thread t = new Thread(tt);  
3.            t.start(); 
New: After a Thread instance is created, the new Keyword and the Thread class or its subclass are used to create a Thread object, at this time, the thread is in the new state, and the thread in the new State has its own memory space, but the thread is not running, and the thread is not alive yet ); runnable: starts a thread by calling the start () method of the thread instance to bring the thread into the ready state (runnable). A ready thread already has the running conditions, but it may not be executed immediately if it is not allocated to the CPU. At this time, it is in the thread-ready queue, waiting for the system to allocate CPCU to it, and the waiting status is not the execution status; at this time, the thread is alive; Running status (running): Once the CPU is obtained (selected by JVM), the thread enters the Running status () the method starts to be executed. In the running state, the thread executes the operations in its own run () method until other methods are called to terminate, or wait for a resource and Blocking, or task completion and death; if the execution does not end in the given time slice, the system will change back to the waiting state of the thread; at this time, the thread is alive ); blocked: The thread is in the blocking status by calling join (), sleep (), wait (), or temporarily using resources; A thread in the Blocking status is still in the alive Dead state (Dead): When the run () method of a thread is completed, interrupted, or unexpectedly exited, this thread reaches the dead state. At this time, there may still be an instance object for this Thread. When this Thready is no longer treated as a Thread that can be executed independently, the independent call stack of the Thread has been dissolved. Once a thread enters the Dead state, it can no longer enter the life cycle of an independent thread. If the start () method is called by a thread in the Dead state, a runtime exception occurs. A thread in the Dead state is not alive ). Thread status chart each class of the thread's Method and Property 1 priority has its own priority. Generally, property is represented by an integer ranging from 1 to 10. The default priority is 5, the highest priority is 10. A thread with a higher priority does not necessarily have a higher chance of execution than a thread with a lower priority, but has a higher chance of execution. By default, the priority of a thread is the same as that of the created thread; 2) Thread. sleep ()/sleep (long millis) current thread sleep/millis time (millis specifies that the sleep time is its minimum non-execution time, because after sleep (millis) sleep arrives, cannot be guaranteed to be immediately scheduled by JVM); sleep () is a static method, so it does not stop other threads and is also in sleep state; thread sleep () will not lose the object lock. Purpose: Keep the object lock and let out the CPU. The call aims to prevent the current thread from occupying the CPU resources obtained by the process alone, so as to leave some time for other threads to execute. 3) thread. yield () gives you the right to use the CPU, give other threads execution opportunities and run threads with the same priority (but it is not guaranteed that the current thread will be rescheduled by JVM and re-entered into the Running state). If there is no thread with the same priority, the yield () method does not work. 4) thread. join () the thread using this method will continue execution after the execution is completed. 5) object. wait () when a thread executes the wait () method, it enters a Waiting Pool related to the object, at the same time, the machine lock of the object is lost-temporarily, and the object lock will be returned after wait. The current thread must have the lock of the current object. If the current thread is not the owner of the lock, the IllegalMonitorStateException will be thrown. Therefore, wait () must be called in the synchronized block. 6) object. Y ()/notifyAll () Wake up the first thread/All threads waiting in the current object waiting pool. Policy ()/policyall () must also have the same object lock. Otherwise, the IllegalMonitorStateException will also be thrown. 7) Synchronizing Block Synchronized Block/method controls access to class member variables. Every object in Java has a unique built-in lock, each Synchronized Block/method can be accessed only when it holds the lock that calls the method to the locked object. Otherwise, the Thread is blocked. The machine lock is dedicated. Once it is held by a Thread, other threads cannot possess the lock (other synchronous methods cannot be accessed). Once a method is executed, the lock is exclusive until the lock is released when the method is returned, then the blocked thread can obtain the lock and re-enter the executable status.

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.