實現多線程的同時復制(三個線程同時復制)


 1 package com.threadcopyfile;
 2 
 3 /**
 4  * @author lisj
 5  * 實現多線程的同時復制
 6  * 調用多個線程同時復制各自的模塊
 7  */
 8 public class threadCopy {
 9     
10     
11     public static void main (String args[]){
12         
13         ThreadCopyFile a=new ThreadCopyFile(1);    //實例化多個線程
14         ThreadCopyFile b=new ThreadCopyFile(2);
15         ThreadCopyFile c=new ThreadCopyFile(3);
16         Thread down1 = new Thread(a);
17         down1.start();            //啟動線程1,2,3
18         Thread down2 = new Thread(b);
19         down2.start();            //
20         Thread down3 = new Thread(c);
21         down3.start();
22             
23     }
24     
25 }
 1 package com.threadcopyfile;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 import java.io.RandomAccessFile;
 6 
 7 /**
 8  * @author lisj
 9  * 實現復制功能
10  * 當線程調用的時候開始復制
11  */
12 public class ThreadCopyFile extends Thread{
13 
14     int i;    //定義全局變量i,識別復制的模塊數
15     
16     ThreadCopyFile(int i)
17     {
18         this.i=i;
19     }
20     
21     
22 /**
23  * 文件復制函數
24  * 利用RandomAccessFile類實現文件的讀和寫
25  * 實現復制文件的功能
26  */
27  public void run() {
28       
29           System.out.println("線程"+i+"運行中。。。");
30     
31           File ofile=new File("e:/java亂碼處理.txt");    
32           File nfile=new File("e:/456.txt");    //定義目的路徑以及文件名
33             
34             try {
35                 
36                 RandomAccessFile in=new RandomAccessFile(ofile,"rw"); 
37                             
38                 long length=in.length()/3;
39                 
40                 RandomAccessFile out=new RandomAccessFile(nfile,"rw");
41                 int count=0;
42                 int len=0;
43                 byte[] b= new byte[2048];
44                 in.seek(length*(i-1));    //設置讀文件偏移位置
45                 out.seek(length*(i-1)); //設置寫文件偏移位置
46                 while(((len=in.read(b))!=-1)&&(count<=(int)length)){    //讀取文件內容設置寫文件停止條件
47                     
48                         out.write(b, 0, len);    
49                         count=count+len;
50                         
51                     }//寫出文件內容
52                         
53             } catch (IOException e) {
54                 
55                 e.printStackTrace();
56             }
57             
58             System.out.println("線程"+i+"復制完成!");
59         }
60   
61     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM