Using blocking queues to control thread set instances in Java _java

Source: Internet
Author: User

Queues manage data in a first-in, first-out way. If you try to add an element to a blocked queue that is already full, or remove an element from an empty blocking queue, it will cause the thread to block. Blocking queues is a useful tool when you are working with multithreading. Worker threads can periodically save intermediate results in a blocking queue. Other worker threads take out the intermediate results and modify them in the future. The queue automatically balances the load. If the first set of threads runs slower than the second, the second line Cheng when it waits for the result. If the first set of threads runs fast, it waits for the second set of threads to catch up.

The following program shows how to use a blocking queue to control the set of threads. The program searches for all files in a directory and all of its subdirectories, printing out a list of files that contain the specified keywords.

The Java.util.concurrent package provides 4 variants for blocking queues: Linkedblockingqueue, Arrayblockingqueue, Priorityblockingqueue, and Delayqueue. We're using a arrayblockingqueue. Arrayblockingqueue requires a given capacity at construction time and can choose whether fairness is required. If the fair parameter is set, the thread with the longest waiting time will be processed first. In general, fairness can make you pay for performance, and use it only when you really need it.

The producer thread enumerates all the files in all subdirectories and puts them in a blocking queue. This is a quick operation, and if the queue is not capped, it will soon contain files that are not found.

We also started a lot of search threads. Each search thread takes a file out of the queue, opens it, prints out all the lines that contain the keyword, and then takes out the next file. We used a little trick to terminate the thread at the end of the work. To emit the completion signal, the enumeration thread puts a virtual object into the queue. (This is similar to putting a virtual package with "last package" on the baggage conveyor belt.) When the search thread takes the virtual object, it is put back and terminated.

Note that there is no need for people to sync any of the displayed threads. In this program, we use the queue data structure as a synchronization mechanism.

Copy Code code as follows:

Import java.io.*;
Import java.util.*;
Import java.util.concurrent.*;

public class Blockingqueuetest
{
public static void Main (string[] args)
{
Scanner in = new Scanner (system.in);
System.out.print ("Enter base directory (e.g./usr/local/jdk1.6.0/src):");
String directory = In.nextline ();
System.out.print ("Enter keyword (e.g. volatile):");
String keyword = in.nextline ();

Final int file_queue_size = 10;
Final int search_threads = 100;

blockingqueue<file> queue = new arrayblockingqueue<file> (file_queue_size);

Fileenumerationtask enumerator = new Fileenumerationtask (queue, new File (directory));
New Thread (Enumerator). Start ();
for (int i = 1; I <= search_threads; i++)
New Thread (New Searchtask (queue, keyword)). Start ();
}
}

/** 
 * This task enumerates all files in a directory and its subdirectories. 
 */
C Lass Fileenumerationtask implements runnable 
{ 
  /** 
    * Cons Tructs a fileenumerationtask. 
    * @param queue the blocking queue to which the enumerated file s are added 
    * @param startingdirectory the directory in which to start the enumeration 
    */
   public fileenumerationtask (blockingqueue<file> queue, File startingdirectory)  
   { 
      this.queue = queue; 
& nbsp;     this.startingdirectory = startingdirectory; 
  } 

   public void Run ()  
   { 
      try
 &nbs p;    { 
         Enumerate (startingdirectory);  
         queue.put (DUMMY); 
      } 
      catch (interruptedexception e)  
    & nbsp { 
     } 
  } 

/**
* Recursively enumerates all files, given directory and its subdirectories
* @param directory the directory in which to start
*/
public void Enumerate (File directory) throws Interruptedexception
{
file[] files = directory.listfiles ();
for (File file:files)
{
if (File.isdirectory ()) enumerate (file);
else Queue.put (file);
}
}

public static File DUMMY = new File ("");

Private blockingqueue<file> queue;
Private File startingdirectory;
}

/**
* This task searches the files for a given keyword.
*/
Class Searchtask implements Runnable
{
/**
* Constructs a searchtask.
* @param queue the queue from which to take files
* @param keyword the keyword for
*/
Public Searchtask (blockingqueue<file> queue, String keyword)
{
This.queue = queue;
This.keyword = keyword;
}

public void Run ()
{
Try
{
Boolean done = false;
while (!done)
{
File File = Queue.take ();
if (file = = Fileenumerationtask.dummy)
{
Queue.put (file);
Done = true;
}
else search (file);
}
}
catch (IOException E)
{
E.printstacktrace ();
}
catch (Interruptedexception e)
{
}
}

/**
* Searches a file for a given keyword and prints all matching lines.
* @param file The file to search
*/
public void Search (file file) throws IOException
{
Scanner in = new Scanner (new FileInputStream (file));
int linenumber = 0;
while (In.hasnextline ())
{
linenumber++;
String line = In.nextline (). Trim ();
if (line.contains (keyword)) System.out.printf ("%s:%d%s%n", File.getpath (), linenumber, line);
}
In.close ();
}

Private blockingqueue<file> queue;
Private String keyword;
}

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.