多线程复制一个文件夹下的所有文件到另一个目录下:
package cn.ba.watchFile.downLoadFile; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * 多线程下载文件 * * 多线程读写文件 * * @author Administrator * */ public class MultiThreadDown { // 最大线程数 public static final Integer MAX_THREAD_NUM = 50; // 固定线程池 static ExecutorService pool = Executors.newFixedThreadPool(MAX_THREAD_NUM); public static void main(String[] args) { File file1 ; /*ReadFile readFile1 = new ReadFile(); pool.execute(readFile1);*/ /* // 创建等待队列 BlockingQueue bqueue = new ArrayBlockingQueue(20); ThreadPoolExecutor threadpool = new ThreadPoolExecutor(6, 11, 2, TimeUnit.MILLISECONDS, bqueue); threadpool.execute(new ReadFile()); */ ReadFile readFile = new ReadFile(); new Thread(readFile, "线程1").start(); new Thread(readFile, "线程2").start(); new Thread(readFile, "线程3").start(); new Thread(readFile, "线程4").start(); new Thread(readFile, "线程5").start(); new Thread(readFile, "线程6").start(); new Thread(readFile, "线程7").start(); new Thread(readFile, "线程8").start(); new Thread(readFile, "线程9").start(); new Thread(readFile, "线程10").start(); } } class ReadFile implements Runnable { List<File> filePathsList = new ArrayList<File>(); int index = 0; public ReadFile() { File f = new File("F:"+File.separator+"zip"+File.separator); getFileList(f); } //文件复制 private void copyFile(File fromFile,File toFile){ try { FileInputStream in = new FileInputStream(fromFile); FileOutputStream os = new FileOutputStream(toFile); byte[] b=new byte[1024]; int n=0; while((n=in.read(b))!=-1){ os.write(b, 0, n); } in.close(); os.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void getFileList(File f) { File[] filePaths = f.listFiles(); for (File file : filePaths) { if (file.isDirectory()) { getFileList(file); }else { if (-1 !=file.getName().lastIndexOf(".zip")) { filePathsList.add(file); } } } } @Override public void run() { // TODO Auto-generated method stub File file=null; while(index<filePathsList.size()){ synchronized (this) { if (index>=filePathsList.size()) { continue; } file=filePathsList.get(index); index++; } try { String osPath="F:"+File.separator+"zipbck"+File.separator+file.getName(); Thread.sleep(30); // FileInputStream is = new FileInputStream(file.getPath()); System.out.println("当前使用的线程是:"+Thread.currentThread().getName()+",正在读文件:"+filePathsList.indexOf(file) +"文件名为:"+file.getName()+",列表当前长度:"+filePathsList.size()); File file1 = new File(osPath); //复制文件 copyFile(file, file1); } catch (Exception e) { // TODO: handle exception } } } }