JAVA multithreading Analysis

Source: Internet
Author: User
Multi-thread Analysis of JAVA-Linux general technology-Linux programming and kernel information. The following is a detailed description. · I. Source and characteristics of the JAVA language
In this era of high-speed information, merchants have made their information and products accessible on the Internet. Behind these unusual web pages, Java is well deserved to be a fully functional, secure, and reliable programming language. Java is a powerful new programming language developed by Sun Microsystem. Is a platform-independent programming language. It is a simple, distributed, interpreted, key-strong, secure, structured neutral, portable, with excellent performance and multithreading. dynamic, language.
Since the advent of Java, Java has been favored by many computer programmers for its simple programming, efficient code, and high portability. Java is a revolutionary programming language on the Internet. It has powerful animation, multimedia, and interaction functions. It has brought World Web into a new era. The Java language is very similar to C ++. It can be used to create secure, portable, and multi-threaded interactive programs. In addition, programs developed using Java are independent of platforms and can be run on multiple platforms. Background Development is an efficient and practical programming method. People can only see the case and calculation results in front of the screen. In fact, the operating system usually schedules some events and manages the flow of programs in the background. For example, the stack in the operating system, resource allocation and management between threads, and memory creation, access, and management. This is not an example. Next we will talk about multithreading.
· II. JAVA multithreading Theory
2.1 Introduction
The multithreading function provided by Java enables multiple small tasks to be executed simultaneously in a program. A thread is also known as a small independent process. Because of the multithreading technology implemented by Java, it is more powerful than C and C ++. The biggest benefit of Multithreading is better interaction and real-time control performance. Of course, the real-time control performance also depends on the system itself (UNIX, Windows, Macintosh, etc.), in terms of development difficulty and performance is better than a single thread. Traditional programming environments are generally single-threaded, Because JAVA is multi-threaded. Although multithreading is a powerful and smart programming tool, it is not easy to use it well and there are many traps that even programmers will inevitably misuse. To better understand the thread, use office staff as a metaphor. The Office staff is like a CPU. They execute jobs according to the instructions of their superiors, just like executing a thread. In a single-threaded environment, each program is written and executed in a way that the program considers only one processing order at any time. In our analogy, it is like the office staff are not disturbing and distracted from start to end, just arranging a job. Of course, in real life, it is difficult for a staff member to have only one task at a time. More often, they need to do several things at a time. The boss handed over the work to the staff, hoping that the staff would do the work and then do the work. If a task cannot be completed, for example, if a staff member waits for information from another department, the staff member places the job aside and transfers it to another job. Generally, the boss wants the staff to make some progress on each task every day. This introduces the concept of multithreading. The multi-threaded programming environment is very similar to this typical office, and several tasks or threads are assigned to the CPU. Like office workers, the computer CPU is not actually able to do a few things at the same time. Instead, the time is allocated to different threads, making every thread a little progress. If one thread cannot be used, for example, if the keyboard input required by the thread has not been obtained, it is transferred to another thread. Generally, the switching between threads of the CPU is very fast, making people feel that all threads are simultaneously performed.
Any processing environment, whether single-thread or multi-thread, has three key aspects. The first is the CPU, which actually performs computer activity, the second is the code of the executed program, and the third is the data of program operations ..
In multi-threaded programming, each thread uses encoding to provide thread behavior, and uses data to provide encoding operations. Multiple Threads can process the same encoding and data at the same time. Different threads may have different encoding and data. In fact, the encoding and data are quite independent and can be provided to the thread as needed. Therefore, several threads often use the same encoding and different data. This idea can also be illustrated by office staff. The accountant may create accounts for one department or several departments. In any case, the accounting task is the same program code, but the data of each department is different. Accounting may be responsible for the entire company's account. At this time, there are several tasks, but some data is shared, because the company account needs data from various departments.
The multi-threaded programming environment uses a convenient model to hide the fact that the CPU is switching between tasks. The model allows you to pretend to have multiple available CPUs. To create another task, the programmer asks another virtual CPU to instruct it to start executing a program segment with a data group. Next we will create a thread.
Thread Creation
It is not difficult to establish a thread in JAVA. Three things are required: the code to be executed, the data to be operated by the code, and the virtual CPU to execute the code. The virtual CPU is packaged in the Thread instance. When creating a Thread object, you must provide the data processed by the executed code and code. JAVA's object-oriented model requires that program code can only be written as a class member method. Data can only exist as automatic (or local) variables or Class Members in the method. These Rules require that the code and data provided for the thread should appear in the form of a class instance.
Public class SimpleRunnable implemants Runable {
Private String message;
Public static void main (String args []) {
SimpleRunnable r1 = new SimpleRunnable ("Hello ");
Thread t1 = new Thread (r1 );
T1.start ();
}
Public SimpleRunnable (String message ){
This. message = message;
}
Public void run (){
For (;;){
System. out. println (message );
}
}
}
When the thread starts execution, it is executed in the public void run () method. This method is the starting point for defining thread execution, just as the application starts from main () and the applet starts from init. The local data operated by a thread is a member of the object passed in to the thread.
First, the main () method constructs an instance of the SimpleRunnable class. Note that the instance has its own data. Here is a String, initialized as "Hello". Because instance r1 is passed into the Thread class constructor, this is the data processed during the Thread runtime. The executed code is run () of the instance method ().
2.2 thread management
A single-threaded program has a main execution body that runs some code. After the program is executed, it exits and the program stops running at the same time. To get the same response in JAVA, we must make slight changes. The program can end only when all threads exit. As long as one thread is running, the program cannot exit. The thread has four States: new, running, wait, and done ). When a thread is created for the first time, it is in the new State. In this state, the thread cannot be run and can only wait. Then, the thread can be started by the method start or sent to the done state. The thread in the done state has ended its execution. This is the last state of the thread. Once a thread is in this state, it cannot appear again. When all threads in the Java Virtual Machine are in the done state, the program is forcibly aborted. All threads currently being executed are in the running state. Some method is used between programs to divide the execution time of the processor into time slices. Every thread in the running state can run, however, each system processor can run only one thread at a given time. Unlike a thread in the running state, you can delete a thread in the waiting state from a set of executable threads for some reason. If the thread execution is interrupted, it will return to the waiting state. Interrupt a thread in multiple ways. The thread can be suspended, waiting on system resources, or being notified to enter sleep state. The thread in this status can return to the running status, or the method stop can also be sent to the done status,
Method
Description
Valid status
Target status
Start ()
Start to execute a thread
New
Running
Stop ()
End execution of a thread
New or running
Done
Sleep (long)
Pause for a period of time, which is a given millisecond
Running
Wait
Sleep (long, int)
Pause for a moment, accurate to nanoseconds
Running
Wait
Suspend ()
Pending execution
Running
Wait
Resume ()
Resume execution
Wait
Running
Yield ()
Explicitly give up execution
Running
Running
2.3 Thread Scheduling
The thread running sequence and the amount of time obtained from the processor mainly depend on the developer. The processor assigns a time slice to each thread, and the running of the thread cannot affect the entire system. The system of the processor thread is either preemptible or non-preemptible. The preemptible system runs the thread with the highest priority at any given time. All threads in the system have their own priority. Thread. NORM_PRIORITY is the default value of the Thread. The Thread class provides the setPriority and getPriority methods to set and read the priority. The setPriority method can be used to change the Thread importance in the Java Virtual Machine. It calls an integer and class Variable Thread. MIN_PRIORITY and Thread. MAX_PRIORITY determines the valid range of this integer. The Java Virtual Machine is preemptible and ensures the thread with the highest running priority. In the Java virtual machine, we change the priority of a thread to the highest, so it will replace the currently running thread, unless the thread ends running or is put into the waiting state by a sleep command, otherwise, all processors will be occupied for a long time. If two threads with the same priority are encountered, the operating system may affect the execution sequence of the threads. The difference depends on the concept of time slicing.
Managing several threads is not a real problem. How does one manage hundreds of threads? Of course, every thread can be executed through a loop, but this is obviously lengthy and tedious. JAVA creates a thread group. A thread group is a pedigree group of threads. Each group contains no restrictions on the number of threads. It can name each thread and be able to execute (Suspend) and Stop (Stop) in the entire thread group) this operation.
2.4 signal flag: Protect other shared resources
This type of protection is called mutex lock. Only one thread can read or modify the data value at a time. When files, especially information databases, are processed, more data is read than written data. In this case, the program can be simplified. For example, assume that there is a database of employee information, including the employee's address, phone number, and other information, which sometimes needs to be modified, but read more data, therefore, we should try our best to prevent data from being damaged or arbitrarily deleted. We introduce the previous concept of mutex lock to allow a read lock and write lock to determine the persons with the right to read data as needed, and when someone wants to write data, there must be a mutex lock, which is the concept of a Signal sign. There are two signal signs: empty () state, indicating that no threads are reading or writing, can accept read and write requests, and provide services immediately; the second state is the reading () state, indicating that a thread is reading information from the database and recording the number of threads performing read operations. When it is 0, the empty state is returned, A write request will cause this thread to enter the waiting state.
Only the empty state can be changed to the writing state. once it enters the writing state, no other thread can perform write operations. Any write or read requests must wait until the thread completes write operations, in addition, the process in the waiting status must wait until the write operation ends. After the operation is complete, return to the empty status and send a notification signal. The waiting thread will get the service.
This signal sign is implemented below
Class Semaphore {
Final static int EMPTY = 0;
Final static int READING = 1;
Final static int WRITING = 2;
Protected int state = EMPTY;
Protected int readCnt = 0;
Public synchronized void readLock (){
If (state = EMPTY ){
State = READING;
}
Else if (state = READING ){
}
Else if (state = WRITING ){
While (state = WRITING ){
Try {wait ();}
Catch (InterruptedException e ){;}
}
State = READING;
}
ReadCnt ++;
Return;
}
Public synchronized void writeLock (){
If (state = EMPTY ){
State = WRITING;
}
Else {
While (state! = EMPTY ){
Try {wait ();}
Catch (InterruptedException e ){;}
}
}
}
Public synchronized void readUnlock (){
ReadCnt --;
If (readCnt = 0 ){
State = EMPTY;
Notify ();
}
}
Public synchronized void writeUnlock (){
State = EMPTY;
Notify ();
}
}
Now is the program to test the signal sign:
Class Process extends Thread {
String op;
Semaphore sem;
Process (String name, String op, Semaphore sem ){
Super (name );
This. op = op;
This. sem = sem;
Start ();
}
Public void run (){
If (op
Catch (InterruptedException e ){;}
System. out. println ("Unlocking readLock:" + getName ());
Sem. readUnlock ();
}
Else if (op
Catch (InterruptedException e ){;}
System. out. println ("Unlocking writeLock:" + getName ());
Sem. writeUnlock ();
}
}
}
Public class testSem {
Public static void main (String argv []) {
Semaphore lock = new Semaphore ();
New Process ("1", "read", lock );
New Process ("2", "read", lock );
New Process ("3", "write", lock );
New Process ("4", "read", lock );
}
}
The testSem class starts from four instances of the process class. It is a thread used to read or write a shared file. The Semaphore class ensures that the access will not damage the file and runs the program. The output result is as follows:
Trying to get readLock: 1
Read op: 1
Trying to get readLock: 2
Read op: 2
Trying to get writeLock: 3
Trying to get readLock: 4
Read op: 4
Unlocking readLock: 1
Unlocking readLock: 2
Unlocking readLock: 4
Write op: 3
Unlocking writeLock: 3
From this we can see that,
2.5 deadlock and how to avoid deadlock:
To prevent concurrent access to data items, the data items should be dedicated and accessed only through the synchronization zone of the instance method of the class itself. To enter the key zone, the thread must obtain the object lock. Assume that the thread needs to exclusively access the data of two different objects, a different lock must be obtained from each object. Now, if the other thread needs to exclusively access these two objects, the process must obtain these two locks before entering. Because two locks are required, a deadlock may occur if you are not careful about programming. Assume that the first thread acquires the Lock of object A and prepares to take the Lock of object B. The second thread acquires the Lock of object B and prepares to take the Lock of object, neither thread can enter, because neither of them can leave the synchronization block that enters, neither of which can discard the lock currently held. Design carefully to avoid deadlocks. When a thread is blocked due to a certain precondition, if the lock mark is required, the stop of the thread cannot change the prohibition condition. To obtain multiple resources, such as the locks of two different objects, you must define the order of obtaining resources. If the locks of objects A and B are always obtained in alphabetical order, there will be no hunger condition mentioned above.
· III. Advantages and Disadvantages of Java Multithreading
JAVA has a complete set of multi-threaded functions, and the benefits it brings are obviously easy to understand. The biggest benefit of Multithreading is better interaction and real-time control performance. Of course, the real-time control performance also depends on the system itself (UNIX, Windows, Macintosh, etc.), in terms of development difficulty and performance is better than a single thread. Of course, a good programming language will inevitably have shortcomings. Because multithreading does not make full use of the basic OS function. As I have mentioned earlier, the above program may have different results for different systems, which may confuse programmers. In the near future, we hope that JAVA multithreading will make full use of the operating system to reduce the confusions of programmers. I look forward to better JAVA.
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.