- import java.io.*;
- class FileDemo2
- {
- public static void main(String []args)
- {
- Object obj = new Object();
- File []file = File.listRoots();
- BufferedWriter bfw;
- try
- {
- bfw = new BufferedWriter(new FileWriter("f:\\exe.txt"));
- }
- catch(Exception e)
- {
- throw new RuntimeException("CreateFile Error!");
- }
- ListDemo ld1 = new ListDemo(file[0],bfw,obj);
- ListDemo ld2 = new ListDemo(file[1],bfw,obj);
- ListDemo ld3 = new ListDemo(file[2],bfw,obj);
- ListDemo ld4 = new ListDemo(file[3],bfw,obj);
- Thread t1 = new Thread(ld1);
- Thread t2 = new Thread(ld2);
- Thread t4 = new Thread(ld3);
- Thread t3 = new Thread(ld4);
-
- t1.start();
- t2.start();
- t3.start();
- t4.start();
-
- try
- {
- bfw.close();
- }
- catch(Exception e)
- {
- throw new RuntimeException("CloseFile Error!");
- }
- }
- }
- class ListDemo implements Runnable
- {
- private File file;
- private BufferedWriter bfw;
- private Object obj;
- ListDemo(File file, BufferedWriter bfw,Object obj)
- {
- this.file = file;
- this.bfw = bfw;
- this.obj = obj;
- }
- public void listDemo(File file,BufferedWriter bfw) throws Exception
- {
- File [] name = file.listFiles();
- if(name != null)
- for(File str: name)
- {
- if(str.isDirectory())
- listDemo(str,bfw);
- else
- {
- if(str.getName().endsWith(".exe"))
- {
- synchronized(obj)
- {
- bfw.write(str.getAbsolutePath()+"...."+str.isHidden());
- bfw.newLine();
- bfw.flush();
- }
- }
- }
- }
- }
- public void run()
- {
- try
- {
- listDemo(file, bfw);
- }
- catch(Exception e)
- {
- throw new RuntimeException("写入文件异常!");
- }
- }
- }
复制代码 我的计划是这样的,每个线程读取一个盘符的文件,都写到一个txt文件中,按理说只有写入时才会有冲突,所以我把写入的那些代码加了锁,可是那些锁好像有问题,
请大家给指点一下应该怎么改!{:soso_e183:}
|
|