Multi-threading programming for improved system performance

Source: Internet
Author: User

Multithreaded programming technology in the practical application of a very broad, multi-threaded technology to improve the utilization of the CPU to help the system to improve performance, then what is the use of multithreaded programming? How to use multithreading? Multi-threaded application must adapt to the specific environment, the thread will greatly increase the burden of the CPU, and the number of threads is less open and difficult to improve the CPU utilization, for this we use the thread pool to manage threads. The thread pool is used to limit the number of threads, reducing the number of times a thread is created and destroyed, each worker thread can be reused, multiple tasks can be performed, and the number of threads in the thread pool may be adjusted according to the system's affordability, preventing the server from being down because of excessive memory consumption. So what is multithreading anyway? to give an image of the metaphor, multithreading is like a human brain, people can do a few things at the same time, for example, I can watch TV while drinking tea, and should not be after watching TV to tea or drink after tea to watch TV, this is the embodiment of multi-threaded life. To give you a more familiar example, if you want to download three movies, most of them are selecting three movies at the same time to download, I believe no one will download it one at a time, we will download the movie while watching the download progress of each movie until all the movies have been downloaded. Of course, the process of downloading movies in these three processes will be affected by network bandwidth, which is also the common resource they need to use. Let's simulate the process of downloading three movies at a time.

1. We open a thread for each movie, the way this thread is implemented I chose to integrate the thread class, overriding its run () method, with the following code:

Package Edu.review.download2;import Java.util.concurrent.executorservice;public Class DownloadFile extends Thread {/* Static variables are used to simulate threads that share resources ******/private static Object obj = new Object ();p rivate String filename;private int filenum = 0; @Overri depublic void Run () {System.out.println ("downloading" + fileName); while (FileNum <) {filenum++; System.out.println ("+ FileName +" "+" downloaded: "+ filenum +"% "); Tempthread ();} if (FileNum >=) {System.out.println ("+ FileName +" "+" download complete); stop (); Resumebynotify ();}} /***** wakes the process of a wait state ******/public void Resumebynotify () {System.out.println (fileName + "action,---notify One"); synchronized ( obj) {obj.notify ();}} /****** wakes all wait status processes *******/public void Resumebynotifyall () {System.out.println (fileName + "Action---full notification"); synchronized (obj) {Obj.notifyall ();}} Public DownloadFile (String fileName) {this.filename = FileName;} /***** the next half of the time, the blocking process *****/private void Tempthread () {if (FileNum = =) {//obj= "false"; synchronized (obj) {try { System.out.println ("+ filename+")The download is blocked due to network reasons, is waiting to wake up "); obj.wait ();//obj.notify ();} catch (Interruptedexception e) {e.printstacktrace ();}}}}

2. Thread execution class Taskexecutor, the code is as follows:

Package Edu.review.download2;import Java.util.concurrent.executors;import Java.util.concurrent.ExecutorService; public class Taskexecutor {public static void main (string[] args) {/**** creates a thread pool with a reusable number of fixed threads *******/executorservice pool = Ex Ecutors.newcachedthreadpool ();/****** creation implements the Runnable interface object, and the thread object also implements the Runnable interface ********/downloadfile t1 = new DownloadFile ("Hans The Great");D ownloadfile t2 = new DownloadFile ("Qin Shihuang Biography");D ownloadfile t3 = new DownloadFile ("Forrest Gump"); T1.setpriority (9); t2.setpriority (5); t3.setpriority (1);/********** the thread into the pool for execution *******/pool.execute (T1); Pool.execute (T2);p Ool.execute (T3),/***** main thread sleep 5 seconds *******/try {thread.sleep (5);} catch (Interruptedexception e) { System.out.println ("Main Thread Interrupted");} System.out.println ("Resume by Notify"); T2.resumebynotifyall ();//close thread pool Pool.shutdown ();}}

the implementation of the above code is to emulate the shared resources in the Obj class, each movie downloaded to half the time the Wait () method called obj block the process, and then through one of the processes of the notifyall () operation to wake up all the threads, so that they re-compete for the use of CPU, Until all the movies have been downloaded. Thread execution class We downloaded three movies at the same time, then opened a thread for each movie's download and put it into the thread pool. The thread pool execution pool manages all the threads in the pool, where I use newcachedthreadpool, which creates a cacheable thread pool. If the size of the thread pool exceeds the thread required to process the task, then a partially idle (60 second non-performing task) thread is reclaimed, and when the number of tasks increases, the thread pool can intelligently add new threads to handle the task. This thread pool does not limit the size of the thread pool, and the thread pool size is entirely dependent on the maximum thread size that the operating system (or JVM) can create. Here is the result when each movie is downloaded to 50%, the thread is blocked, and one of the threads performs a wake-up operation, and all the threads re-enter the execution state completion (due to the large amount of data only partially):




By comparing the output results we can find the same as the results of our previous analysis, this is the multi-threaded implementation of multiple file Download example, I hope to be helpful to everyone.



Multi-threading programming for improved system performance

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.