一 线程池
       向I/0受限的程序,使用多线程会极大地提高性能。 但是线程有着自己的开销,启动一个线程和
       结束一个线程会耗费虚拟机大量的工作。
  
二  解决方法 
   
       通过使用重用线程的方法,来达到两全其美的效果。把所有需要完成的任务放在队列或者其他的数据结构中,让每个线程完成前面的任务之后,
        再从队列中获取新的任务,这就称为线程池 ,保存任务的数据结构叫做池 (pool) 。
   
  三 实现方法 :

       1   第一次分配固定数量的线程,当池空时,每个线程都在池中等待。 当向池添加一个任务的时候,所有等待的进程
            得到通知,当一个线程结束其分配的任务时,它再回到池中取新的任务,如果没有得到他就等待,直到新的任务
            添加到池中。
        2    将线程本身放在池中,让主线程从池中取出线程,为其分配任务。如果必须要完成某项任务,而池中没有线程的时候,
               主程序就会成为一个新的线程。每个线程结束之后,都会返回到池中。
  
四  实例 :  压缩指定文件夹内的所有文件 

                  1  首先读取文件夹中的文件,这是一个I/O密集型的操作。
                  
                 2   而数据压缩则是一个CPU密集型操作 。
                       所以这时候 就需要线程池。 主程序负责确定压缩哪个文件,而客户端程序进行具体的压缩的工作。
                       
                   
五 步骤 
        
              首先填充池,然后启动池中的压缩文件的线程,

 六   代码 
       
          采用的方法是 四 的第一种方法,即首先出示化一个线程组,然后创建一个任务池,池中存储的是所要读取的
         文件 , 每当池空的时候,判断时候结束,没有结束的话,就等待在pool。 
        
         池不空的情况下就从池中弹出一个任务,处理。

          值得注意的是  , 如何判断文件压缩是否完成






package cn.bupt.pool;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.zip.GZIPOutputStream;

public class GZipThread extends Thread{

    
      
private List pool ;
      
private static int filesCompressed = 0 ;
      
      
public GZipThread(List pool){
          
this.pool = pool;
      }

      
      
      
private static synchronized void incrementFilesCompressed()
      
{
         filesCompressed
++ ;
                    
      }

      
      
      
public void run()
      
{
          
while(filesCompressed != GZipAllFiles.getNumberOfFilesToBeCompressed())
          
{
              File input 
= null ;
              
synchronized (pool){
                  
                  
while(pool.isEmpty())
                  
{
                      
if(filesCompressed == GZipAllFiles.getNumberOfFilesToBeCompressed())
                      
{
                          System.out.println(
"Thread ending");
                          
return ; 
                          
                      }

                      
                      
try {
                        pool.wait() ;
                    }
 catch (InterruptedException e) {
                        
// TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                  }

                  
                  input 
= (File) pool.remove(pool.size() - 1) ;
                  incrementFilesCompressed();
              }

              
              
              
/*不压缩已经压缩过的文件*/
              
if(!input.getName().endsWith(".gz")){
                  
                  InputStream in 
= null;
                
try {
                    in 
= new FileInputStream(input);
                }
 catch (FileNotFoundException e) {
                    
// TODO Auto-generated catch block
                    e.printStackTrace();
                }

                  in 
= new BufferedInputStream(in) ;
                  
                  
/*设置压缩后保存的文件*/
                  File output 
= new File(input.getParent() , input.getName() + ".gz") ;
                  
                  
if(!output.exists()){
                      
                      OutputStream out 
= null;
                    
try {
                        out 
= new FileOutputStream(output);
                    }
 catch (FileNotFoundException e) {
                        
// TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                      
try {
                        out 
= new GZIPOutputStream(out) ;
                    }
 catch (IOException e) {
                        
// TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                      out 
= new BufferedOutputStream(out) ;
                      
int b ;
                      
try {
                        
while((b = in.read())!= -1)
                            
try {
                                out.write(b) ;
                            }
 catch (IOException e) {
                                
// TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                    }
 catch (IOException e1) {
                        
// TODO Auto-generated catch block
                        e1.printStackTrace();
                    }

                      
try {
                        out.flush() ;
                    }
 catch (IOException e) {
                        
// TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                      
try {
                        out.close() ;
                    }
 catch (IOException e) {
                        
// TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                      
try {
                        in.close()  ;
                    }
 catch (IOException e) {
                        
// TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                      
                                        
                  }

                                                      
              }
                                
          }

                
      }

      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
}



 九 主类代码

     
package cn.bupt.pool;

import java.io.File;
import java.util.Vector;

public class GZipAllFiles {

    
/* 连接的线程数目 */
    
public final static int THREAD_COUNT = 4;
    
private static int filesToBeCompressed = -1;

    
/**
     * 
@param args
     
*/

    
public static void main(String[] args) {
        
// TODO Auto-generated method stub

        Vector pool 
= new Vector();

        
/*
         * 初始化线程数组
         
*/

        GZipThread[] threads 
= new GZipThread[THREAD_COUNT];

        
for (int i = 0; i < threads.length; i++{

            threads[i] 
= new GZipThread(pool);
            threads[i].start();
        }


        
int totalFiles = 0;
        
for (int i = 0; i < args.length; i++{
            File f 
= new File(args[i]);
            
if (f.exists()) {
                
if (f.isDirectory()) {
                    File[] files 
= f.listFiles();
                    
for (int j = 0; j < files.length; j++{
                        
/* 不递归处理目录 */
                        
if (!files[j].isDirectory()) {
                            totalFiles
++;
                            
synchronized (pool) {
                                pool.add(files[j]);
                                pool.notifyAll();
                            }

                        }


                    }


                }


                
/* 如果是一个单独的文件 */
                
else {
                    totalFiles
++;
                    
synchronized (pool) {
                        pool.add(
0, f);
                        pool.notifyAll();

                    }

                }

            }

        }


        filesToBeCompressed 
= totalFiles;
        
/*
         * 确保让所有的线程知道没有更多的文件会添加到池中
         
*/

        
for (int i = 0; i < threads.length; i++{
            threads[i].interrupt();
        }

    }


    
public static int getNumberOfFilesToBeCompressed() {

        
return filesToBeCompressed;
    }


}








































  






    
   
posted on 2010-07-14 21:08 buptduming 阅读(500) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: