Multi-threaded search and sorting

Source: Internet
Author: User
Tags cas thread class

Foreword: Multi-threaded search array and sorting is a very common scenario in real development, we may save some business data through an array, search to reach the data we want or sort the data according to certain business rules, and the most common technique in technology selection is the for loop traversal and various sorting algorithms. This search/Sort technique is simple, and what we're going to talk about today is how to use multi-threaded search and sequencing, how to take advantage of multithreading to efficiently complete the search and sequencing is the focus of this blog focus

This blog directory

One: Multi-threaded search

Second: the thread sort

Three: summary

One: Multi-threaded search

1.1: Create a thread pool

in order to improve the performance of multi-threaded, we put the thread pool centralized management, so as to minimize the thread switching brought by small. There are 5 thread pool types, here we choose to use the cached cache pool, first define the number of threads is 2, that is, each expansion of two threads to search. To prevent a thread from finding a value, and other threads continue to work, we can use Atomicinteger's unlocked CAs to save the returned results, avoiding a thread searching for values, and other threads continuing the search. In defining an array, note that there are only 13 array elements here, the number of arrays is small, and the multi-threaded performance search promotion is not obvious .

 Public classManythreadsearch { Public StaticExecutorservice pool = Executors.newcachedthreadpool ();//Create a cache thread pool     Public Static Final intthread_num=2;//defines the number of threads as 2     Public StaticAtomicinteger result=NewAtomicinteger (-1);//The resulting value returned by default is-1    Private Static int[] array={2,8,5,3,8,9,3,4,26,76,46,8};//array of searches

1.2: Search Method

This is also the case with a for loop, and instead of defining the begin and end points, the thread will search in that interval. If one of the threads finds a value, the value of result is set to the subscript value of the found element by CAS technology, and the expect expected value is-1, which is the default value of result. Students who do not understand, please refer to the previous blog to learn about CAS technology. Collation logic is relatively simple, that is, for loop lookup, Note: This method is the method that each thread will call.

  /*** Search Method *@paramvalue of Searchvalue search *@parambeign Start *@paramEnd *@returnindex of the search element*/     Public Static intSearchintSearchvalue,intBeign,intend) {        intI=0;  for(i=beign;i<end;i++){            if(Result.get () >0){                returnResult.get (); }            if(array[i]==searchvalue) {                if(Result.compareandset ( -1,i)) {//prevent threads from repeating searches with CAs                    returnResult.get (); }                returnI//returns the element subscript            }        }        return-1; }

1.3: Search Thread

The search thread is a single thread for the search, which inherits the class from callable instead of thread, mainly because we want to borrow the future pattern, and because the search is going to have a return value, the thread's Run method cannot have a return value. Some fixed values are then passed to the thread class through the constructor method, and the search method is called in the call method to get the return value.

    /*** Search thread does not use thread here, because thread cannot have return value*/     Public Static classSearchthreadImplementsCallable<integer> {        Private intBeginintEndintSearchvalue;  PublicSearchthread (intSearchvalue,intBeginintend) {             This. Begin =begin;  This. end =end;  This. Searchvalue =Searchvalue; } @Override PublicInteger Call ()throwsException {//The call method is like the Run method in thread            intRe=search (searchvalue,begin,end); returnre; }    }

1.4: The final search method

This method only needs to pass in a search value, where the array is cut, by the number of threads and arrays of the size of the automatic allocation of sub-arrays, each thread to search for a fixed sub-array, and then return the results, there is a future, the future represents the final search results, Where one thread returns the result, the other thread stops the search immediately.

 /*** Method of searching with threads *@paramvalue of Searchvalue search *@return     * @throwsexceptions performed by Executionexception *@throwsInterruptedexception The exception that was interrupted*/     Public Static intEserach (intSearchvalue)throwsexecutionexception, interruptedexception {//subarrsize=3;        intSubarrsize = array.length/thread_num + 1; ArrayList<Future<Integer>> result =NewArraylist<>();  for(inti = 0; i < Array.Length; i+=subarrsize) {            intend=i+subarrsize; if(end>array.length) {End=Array.Length; } Future<Integer> future = Pool.submit (NewSearchthread (searchvalue,i, end));//The thread pool starts working, commits the threads, saves all the result values returnedResult.add (future); }         for(future<integer>Fu:result) {            if(Fu.get () >=0){                returnFu.get (); }        }        return-1; }

Two: multi-threaded sorting

2.1: Preface

Sorting is also very common in our daily programming, such as MySQL sorting, sorting by time, ID, and of course MySQL internal use of B + tree sort. There are a lot of sorting algorithms, such as bubble sorting, quick sorting, heap sorting, and so on, we do a simple interview question: to an array, will be odd and even separated, this quick sort of idea is easy time, of course, the topic of this blog is multi-threading, So let's explore the use of multithreading to sort arrays

2.2: Bubble Sort Review

Bubble sort can be said to be the simplest sort algorithm, similar to the nature of small bubbles at the bottom, the atmosphere bubbles in the front of the phenomenon, the array from small to large comparison exchange sort

 /*** Bubble Sort *@paramarr Array*/     Public Static voidBubblesort (int[] arr) {         for(inti = arr.length-1; I >0;--) {             for(intj=0;j<i;j++) {//Swap Array Order                                if(arr[j]>arr[j+1]) {                    inttemp =Arr[j]; ARR[J]= Arr[j + 1]; Arr[j+ 1] =temp; }            }        }    }

2.3: Odd-even index separation sorting algorithm

The idea of the odd and even index separation sorting algorithm is to divide the array into odd and even indexes by index, then divide the threads, some sort only by odd index, some sort only by an even index, and then merge the results together so that they do not affect each other and implement sorting. You can see that the following code first creates a cached thread pool, and then defines an array, which is used to indicate whether the data exchange occurred, and when the flag is set with the Synchronzied lock control, the purpose is to put a multi-threaded concurrency disorder problem.

/*** Created by Yiron on 7/10 0010. * * @desc multi-threaded sorting*/ Public classManythreadsort { Public StaticExecutorservice pool = Executors.newcachedthreadpool ();//Create a cache thread pool;     Public Static int[] Array = {1, 7, 56, 45, 45, 34, 343, 4, 9, 35, 45, 45};  Public Static intflag = 1;//whether the token for data exchange occurs     Public Static synchronized voidSetflag (intExpect) {//lock control prevents flags from being overwritten by other threadsFlag=expect; }     Public Static synchronized intGetflag () {returnFlag; }

2.4: Data Interchange Thread

Define a thread that is specifically used for odd and even index sorting, where two variables are used, one is the index of the array, and the other is Countdownlatch, the function of which is to control the thread wait, similar to join, where each exchange of data will call its Countdown method, Set the counter-1 until the counter is 0 to release all waiting threads

 Public Static classOddevensortthreadImplementsRunnable {inti;        Countdownlatch latch;  PublicOddevensortthread (intI, Countdownlatch latch) {             This. i =i;  This. Latch =latch; } @Override Public voidrun () {if(Array[i] > array[i + 1]) {//if the preceding array element is greater than the subsequent element, the interchange order                inttemp =Array[i]; Array[i]= Array[i + 1]; Array[i+ 1] =temp; Setflag (1);        } latch.countdown (); }    }

2.5: Sorting algorithm

In this sorting algorithm, where the function of start is to indicate whether the process is an odd or even interchange, 0 means an even interchange, 1 for an odd interchange, the start of the program, the first is the data exchange or odd exchange cases, and then the first place flag 0, indicating that no data exchange occurred, Create a counter that is One-second minus a fixed value for the length of the array, which determines the size of the fixed value, minus 1 if it is an even number, minus 0;

/*** Sorting Algorithm * *@paramArray Arrays *@throwsinterruptedexception*/     Public Static voidEsort (int[] Array)throwsinterruptedexception {intStart = 0;  while(Getflag () = = 1 | | start = 1) {Setflag (0); Countdownlatch Countdownlatch=NewCountdownlatch (ARRAY.LENGTH/2-(array.length% 2 = = 0? start:0));  for(inti = start; i < array.length-1; i + = 2) {Pool.submit (NewOddevensortthread (i, Countdownlatch));            } countdownlatch.await (); if(Start = = 0) {Start= 1; } Else{Start= 0; }        }    }

The running program can discover that the thread has sorted the array:

1 4 7 9 34 35 45 45 45 45 56 343
Process finished with exit code

Three: summary

This blog tells the array of multi-threaded search and sequencing techniques, where thread scheduling uses the thread pool's cachedthreadpool, and in order to use the Coutdownlatch this threading tool class, which is somewhat similar to join, but more powerful than join. It is worth mentioning that if the size of the array is small, the performance improvement of multithreading is not very large, or even less than a single-threaded program, but once the data volume is particularly large, the role of multithreading is obvious to play out. Of course this blog is just a little bit, just a few of the techniques of multithreading. I will continue in the post-threading here to explore, thank you.

Multi-threaded search and sorting

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.