Java multi-threading, thread pool,

1. Method of creating a thread pool of three:

    // For each task, if there is a free thread is available immediately let his mandate,
     // no idle threads create a thread. 
    The pool = ExecutorService Executors.newCachedThreadPool ();
     // fixed size thread pool, the number of tasks> idle threads, tasks in a queue unserved 
    ExecutorService the pool = Executors.newFixedThreadPool;
     // degradation of the size of the thread pool 1 , submitted by a task-by-thread execution. 
    ExecutorService pool = Executors.newSingleThreadPool ();

2. Assign the task to the thread pool:

    // The returned object can call isDone (), the Cancel (), isCancelled 
    Future <?> The Submit (Runnable Task);
     // GET () Returns the specified result object 
    Future <T> the Submit (Runnable Task, T result);
     / / objects returned in the results are ready to get it. 
    Future <T> submit (Callable < T> task);

3. run out when a thread pool, call shutdown () to start the thread pool shutdown sequence. The actuator is switched off no longer accept new tasks, when the tasks are completed, the thread pool thread death.

4. Case: Given a directory, the directory to find the number of Chinese in this document is a document that contains the specified keywords.

  Conditions: directory, keyword

  4.1 Task class (thread class)

   / ** threaded task: the number of all the files containing a given keyword directory calculations. * / 
   Class MatchCounter the implements a Callable <Integer> 
   { 
      Private File Directory;
       Private String keyword;
       Private ExecutorService the pool;
       Private  int COUNT; 

      / ** 
       * Constructs A MatchCounter. 
       * @Param Directory given directory 
       * @param keyword keyword 
       * @ param the pool thread pool used to perform tasks
        * / 
      public MatchCounter (File Directory, String keyword, ExecutorService the pool) 
      { 
         the this= .directory Directory;
          the this .keyword = keyword;
          the this .pool = the pool; 
      } 

      @Override 
      public Integer Call () 
      { 
         COUNT = 0 ;
          the try 
         { 
            File [] Files = directory.listFiles ();
             // thread execution result set 
            List <Future <Integer >> Results = new new ArrayList <> (); 

            for (file file: files)
                // iterate to all files in a given directory
                // If the folder 
               if(file.isDirectory ()) 
               { 
                  // recursive 
                  MatchCounter counter = new new MatchCounter (File, keyword, the pool); 
                  Future <Integer> = Result pool.submit (counter); 
                  results.add (Result); 
               } 
               // if the file , call the search () method to see if contains the keyword. 
               the else 
               { 
                  IF (Search (File)) COUNT ++ ; 
               } 

            for (Future <Integer> Result: Results)
                the try 
               { 
                  int A = result.get (); 
                  COUNT + = result.get();
               }
               catch (ExecutionException e)
               {
                  e.printStackTrace();
               }
         }
         catch (InterruptedException e)
         {
         }
         return count;
      }

      /**
       * Searches a file for a given keyword.
       * @param file the file to search
       * @return true if the keyword is contained in the file
       */
      public boolean search(File file)
      {
         try
         {
            try (Scanner in = new Scanner(file, "UTF-8"))
            {
               boolean found = false;
               while (!found && in.hasNextLine())
               {
                  String line = in.nextLine();
                  if (line.contains(keyword)) found = true;
               }
               return found;
            }
         }
         catch (IOException e)
         {
            return false;
         }
      }
   }

  4.2 The main program

  

    public  class ThreadPoolTest 
   { 
      public  static  void main (String [] args) throws Exception 
      { 
         the try (Scanner in = new new Scanner (System.in)) 
         { 
            System.out.print ( "Please enter the directory you want to find:" ); 
            String Directory = in.nextLine (); 
            System.out.print ( "Please enter a keyword to find:" ); 
            String keyword = in.nextLine (); 
      
            ExecutorService the pool = Executors.newCachedThreadPool (); 
      
            MatchCounter counter =new MatchCounter(new File(directory), keyword, pool);
            Future<Integer> result = pool.submit(counter);
      
            try
            {
               System.out.println(result.get() + " 匹配的文件");
            }
            catch (ExecutionException e)
            {
               e.printStackTrace();
            }
            catch (InterruptedException e)
            {
            }
            pool.shutdown();
      
            int largestPoolSize = ((ThreadPoolExecutor) pool).getLargestPoolSize();
            System.out.println("Maximum number of thread pool =" + largestPoolSize); 
         } 
      } 
   }

  4.3 operating results:

  

 

Guess you like

Origin www.cnblogs.com/lovleo/p/11320901.html