日期:2014-05-20 浏览次数:20696 次
import java.io.*;
import java.util.*;
import java.util.zip.*;
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() {
// 所有线程同步同一个class对象,操作同一个静态filesCompressed
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();//得到通知,获得所等待的锁就执行wait()后面的语句
} catch (InterruptedException ex) {
}
}//while (pool.isEmpty())循环结束
input = (File) pool.remove(pool.size() - 1);
incrementFilesCompressed();
}//synchronized (pool)同步结束
if (!input.getName().endsWith(".gz")) {// 不压缩已经压缩过的文件
try {
InputStream in = new FileInputStream(input);
in = new BufferedInputStream(in);
File output = new File(input.getParent(), input.getName()
+ ".gz");
if (!output.exists()) {// 不覆盖已经存在的文件
OutputStream out = new FileOutputStream(output);
out = new GZIPOutputStream(out);
out = new BufferedOutputStream(out);
int b;
while ((b = in.read()) != -1)
out.write(b);
out.flush();
out.close();
in.close();
}
} catch (IOException ex) {
System.err.println(ex);
}
}
}//最外层while结束
}//run()结束
}
import java.io.*;
import java.util.*;
public class GZipAllFiles {
public final static int THREAD_COUNT = 4;
public static int filesToBeCompressed = -1;
public static void main(String[] args) {
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;i++){
if(!files[j].isDirectory()){//不递归处理目录
totalFiles++;
synchronized(pool){
pool.add(0, files[j]);
pool.notifyAll();
}
}
}//内层for结束
}//****处for结束
else{
totalFiles++;
synchronized(pool){
pool.add(0,f);
pool.notifyAll();
}
}//else结束
}
}//最外层for结束
filesToBeCompressed=totalFiles;
for(int i=0;i<threads.length;i++){//没有文件再添加到池中,中断等待的线程
threads[i].interrupt();
}
}
public static int getNumberOfFilesToBeCompressed() {