多線程復制一個文件夾下的所有文件到另一個目錄下:
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 } } } }