Multi-threaded Multi-core Java multi-thread programming technology analysis

Source: Internet
Author: User
Multi-threaded Multi-core Java multi-threaded programming technology analysis-general Linux technology-Linux programming and kernel information, the following is a detailed description. I. multithreading technology in the Java environment

Building a threaded application often has an important performance impact on the program. For example, consider a program that reads a large amount of data from the disk and processes the data before writing them to the screen (such as a DVD player ). In a traditional single-threaded Program (most of the client programs used today), only one task is executed at a time, and each of these activities occurs as different stages of a sequence respectively. Data can be processed only when a piece of data with a defined size is read. Therefore, the program logic that can process data is not executed until the disk read operation is complete. This will cause very poor performance problems.

In a multi-threaded program, you can allocate a thread to read data, let another thread process data, and let the third thread send data to the graphics card. These three threads can run in parallel. In this way, data can still be processed while reading data from the disk, thus improving the overall program performance. Many examples can be designed to do two things at the same time to further improve performance. Java Virtual Machine (JVM) is widely used for this reason.

This article will discuss how to create multi-threaded Java code and some best practices for parallel programming. It also introduces some tools and resources that are extremely useful to developers. Due to space limitations, it is impossible to fully discuss these issues. Therefore, I would like to focus on the important points and provide you with relevant reference information.

Ii. Threaded Java code

All programs use at least one thread. In C/C ++ and Java, this refers to the thread started by calling main. In addition, several steps are required to create a thread: Create a New thread and specify a job for it. Once the work is completed, the thread will be automatically killed by JVM.

Java provides two methods to create threads and specify them to work. The first method is to subclass the Java Thread class (in the java. lang Package), and then use the worker function of the Thread to overload the run () method. The following is an example of this method:

Public class SimpleThread extends Thread {
Public SimpleThread (String str ){
Super (str );
}
Public void run (){
For (int I = 0; I <10; I ++ ){
System. out. println (I + "" + getName ());
Try {
Sleep (long) (Math. random () * 1000 ));
} Catch (InterruptedException e ){}
}
System. out. println ("DONE! "+ GetName ());
}
}

This class subclass Thread and provides its own run () method. The function in the code above runs a loop to print the transmitted string to the screen, and then waits for a random number of times. After 10 cycles, the function prints "DONE! ", Then exit-and it will kill this thread. The main function for creating a thread is as follows:

Public class TwoThreadsDemo {
Public static void main (String [] args ){
New SimpleThread ("Do it! "). Start ();
New SimpleThread ("Definitely not! "). Start ();
}
}

Note that this code is extremely simple: The function starts with a given name (which is the string that the thread will print out) and calls start (). Then, start () will call the run () method. The program results are as follows:

0 Do it!
0 Definitely not!
1 Definitely not!
2 Definitely not!
1 Do it!
2 Do it!
3 Do it!
3 Definitely not!
4 Do it!
4 Definitely not!
5 Do it!
5 Definitely not!
6 Do it!
7 Do it!
6 Definitely not!
8 Do it!
7 Definitely not!
8 Definitely not!
9 Do it!
DONE! Do it!
9 Definitely not!
DONE! Definitely not!


As you can see, the output results of these two threads are combined. In a single-threaded program, all "Do it! "The command will be printed together, followed by the output" Definitely not! ".

Different operations of this program will produce different results. This uncertainty comes from two aspects: There is a random pause in the loop; more importantly, the thread execution time cannot be guaranteed. This is a key principle. JVM will run these processes according to its own schedule (virtual machines generally support running these threads as quickly as possible, but there is no way to ensure when a given thread is running ). Each thread can associate a priority with it to ensure that the key thread is processed by JVM before the secondary thread.

The second way to start a thread is to use a class that implements the Runnable interface, which is also defined in java. lang. This Runnable interface specifies a run () method-then the method becomes the main function of the thread, similar to the previous code.

Currently, the general style of Java programs is to support inherited interfaces. By using interfaces, a class can still be inherited (subclass) in the future-if necessary (for example, if the class is to be used as an applet in the future, this will happen ).


Iii. Thread meaning

The multi-thread technology is used to enhance the performance, while it also increases the complexity of the internal operation of the program. This complexity is mainly caused by interactions between threads. It is important to be familiar with these problems, because as more and more core chips are added to Intel processors, the number of threads to be used will also increase accordingly. If you cannot understand these problems well when creating a multi-threaded program, it is difficult to find errors during debugging. Therefore, let's take a look at these problems and their solutions.

Wait for another thread to finish: Suppose we have an integer array to process. We can traverse this array and execute the corresponding operation each time with an integer. Or, more efficiently, we can create multiple threads so that each thread can process part of the array. Suppose we have to wait until all threads end before starting the next step. To temporarily synchronize activities between threads, these threads use the join () method, which enables one thread to wait for the completion of another thread. The added thread (thread B) waits for the completion of the added thread (thread. An optional timeout value in join () allows thread B to continue processing other work-if thread A has not been terminated within the specified time frame. This problem will touch on the core complexity of the thread-the issue of waiting for the thread. Next we will discuss this issue.

Wait on the locked object: Let's write an airline seat distribution system. When developing such a large program, it is often necessary to assign a thread to each user connected to the software. For example, a thread corresponds to a ticket salesman (in a large system, this is not always the case ). If two users want to allocate the same seat at the same time, the problem may occur. Unless special measures are taken, one thread will allocate this seat, and the other thread will be doing the same thing. Both users will think that they have an allocated seat on this flight.

To prevent two threads from modifying the same data item at the same time, let a thread lock the data item before modifying the data. In this way, when the second thread starts to modify, it will wait until the first thread releases the lock. When this happens, the thread will see that the seat has been allocated, and the request for the seat allocation will fail. Two threads compete to allocate seats, that is, the famous competition condition. When competition occurs, the system may leak. To this end, the best way is to lock any code-the Code accesses a variable that can be shared by multiple threads.

There are several lock options in Java. The most commonly used is the synchronization mechanism. When a method signature includes synchronization, only one thread can execute this method at any given time. Then, when the method is executed, the lock on the method is removed. For example,

Protected synchronized int reserveSeat (Seat seat_number ){
If (seat_number.getReserved () = false ){
Seat_number.setReserved ();
Return (0 );
}
Else return (-1 );
}

Is a method-in this method, only one thread is run at a time. This lock mechanism breaks the competition conditions described above.

Synchronization is one of several ways to process interaction between threads. Several convenient methods are added to J2SE 5.0 to lock objects. Most of these methods can be found in the java. util. concurrent. locks package-once you are familiar with the Java thread, you should study it in detail.

While the lock mechanism solves the competition conditions, they also bring new complexity. In this case, the most difficult problem is the deadlock. Assuming that thread A is waiting for thread B and thread B is waiting for thread A, the two threads will be locked forever-this is the meaning of the term deadlock. The deadlock issue may be difficult to determine and must be very careful to ensure that such dependency is not found between threads.

4. Use thread pool

As mentioned above, when a thread completes execution, the memory allocated to it will be killed by JVM and recycled by the garbage collection mechanism. The trouble of constantly creating and destroying threads is that it wastes the clock cycle, because it takes extra time to create threads. A common and best implementation is to allocate a group of threads (called a thread pool) early in the program running, and then use them when these threads are available. By using this scheme, the function assigned to a thread during creation is to stay in the thread pool and wait for a job to be allocated. Then, when the allocation is completed, the thread is returned to the thread pool.

J2SE 5.0 introduces the java. util. concurrent package-it includes a pre-built thread pool framework-which greatly facilitates the implementation of the above method. For more information about the Java thread pool and a tutorial, see http://java.sun.com/#/jdctechtips/2004/tt1116.html#2.

When designing thread programs and thread pools, the question about how many threads should be created naturally arises. The answer is how you plan to use these threads. If you divide jobs by threads Based on Separated tasks, the number of threads is equal to the number of tasks. For example, a word processor may use one thread for display (the main program thread in almost all systems is responsible for updating the user interface), one for marking the document, and the third for spelling check, the fourth is used for other background operations. In this case, it is ideal to create four threads and they provide a natural way to write such software.

However, if the program-as discussed earlier-uses multiple threads for similar work, the optimum number of threads will be a reflection of system resources, in particular, the number of executable pipelines on the processor and the number of processors are reflected. On systems using Intel processor hyper-Threading Technology (HT technology), there are currently two execution pipelines on each processor core. The latest multi-core processor has two processor cores on each chip. Intel pointed out that chips may have multiple cores in the future, most of which are due to higher performance and will not fundamentally increase the consumption of heat or power. Therefore, the number of pipelines will increase.

According to the arithmetic recommendations made by the above architecture, four execution pipelines can be used and thus four threads can be used on a dual-core Pentium 4 processor system to provide ideal performance. In a dual-processor Intel Xeon? The ideal number of threads on the CPU workstation is 4, because the Xeon chip currently provides HT technology but does not provide a multi-core model. You can refer to the document below to learn about the number of execution pipelines on these new processors (http://www.intel.com/cd/ids/developer/asmo-na/eng/196716.htm ).

V. Summary

When you run a threaded Java program on the platform, you may want to monitor the loading process and thread execution on the processor. One of the best JVMs for getting this data and managing how the JVM processes parallel processing is BEA's WebLogic JRockit. JRockit also has other advantages that BEA and Intel engineers specifically design and optimize the Intel Platform.

Regardless of which JVM you use, intel's VTune Performance Analyzer will give you an in-depth view of how JVM executes your code-including the Performance bottleneck of each thread. In addition, Intel provides a white paper on how to use VTune Performance Analyzer in a Java environment [PDF 2 MB].

In short, this article provides an analysis of the working mechanism of threads on the Java platform. As Intel will continue to produce HT technology processors and release more core chips, the pressure to get performance benefits from these multi-channels will also increase. In addition, as the number of core chips increases, the number of pipelines increases accordingly. The only way to take advantage of them is to use multithreading technology, as discussed in this article. In addition, the advantages of Java multi-threaded programs become more and more obvious.
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.