在java中的两个线程之间传递字符串

时间:2010-05-20 14:49:01

标签: java multithreading file

我必须在文件中搜索字符串并将匹配的行写入另一个文件。 我有一个线程来读取文件和一个线程来写一个文件。我想从read线程发送stringBuffer到写线程。请帮我通过这个。我正在传递空值。

写线程:

class OutputThread extends Thread{

    /****************** Writes the line with search string to the output file *************/
        Thread runner1,runner;
        File Out_File;

        public OutputThread() {
        }
        public OutputThread(Thread runner,File Out_File) {
            runner1 = new Thread(this,"writeThread"); // (1) Create a new thread.
            this.Out_File=Out_File;
            this.runner=runner;
            runner1.start(); // (2) Start the thread.
        }


        public void  run()
        {

             try{
            BufferedWriter bufferedWriter=new BufferedWriter(new FileWriter(Out_File,true));
           System.out.println("inside write");
            synchronized(runner){
                System.out.println("inside wait");
                runner.wait();
            }
            System.out.println("outside wait");
            // bufferedWriter.write(line.toString());
            Buffer Buf = new Buffer();
            bufferedWriter.write(Buf.buffers);
            System.out.println(Buf.buffers);
            bufferedWriter.flush();

             }
             catch(Exception e){
             System.out.println(e);
             e.printStackTrace();
             }

        }
}

阅读Thraed:

class FileThread extends Thread{     

     Thread runner;
     File dir;
     String search_string,stats;
     File Out_File,final_output;
     StringBuffer sb = new StringBuffer();

        public FileThread() {
        }
        public FileThread(CountDownLatch latch,String threadName,File dir,String search_string,File Out_File,File final_output,String stats) {
            runner = new Thread(this, threadName); // (1) Create a new thread.
            this.dir=dir;
            this.search_string=search_string;
            this.Out_File=Out_File;
            this.stats=stats;
            this.final_output=final_output;
            this.latch=latch;
            runner.start(); // (2) Start the thread.
        }

      public void run()
      {

        try{
        Enumeration entries;
        ZipFile zipFile;
        String source_file_name = dir.toString();
        File Source_file = dir;
        String extension;
        OutputThread out = new OutputThread(runner,Out_File);

        int dotPos = source_file_name.lastIndexOf(".");
        extension = source_file_name.substring(dotPos+1);

        if(extension.equals("zip"))
        {
          zipFile = new ZipFile(source_file_name);
          entries = zipFile.entries();
          while(entries.hasMoreElements()) {
             ZipEntry entry = (ZipEntry)entries.nextElement();
             if(entry.isDirectory()) {
                 (new File(entry.getName())).mkdir();
                 continue;
                }
              searchString(runner,entry.getName(),new BufferedInputStream(zipFile.getInputStream(entry)),Out_File,final_output,search_string,stats);

          }

          zipFile.close();
         }

         else
          {

            searchString(runner,Source_file.toString(),new BufferedInputStream(new FileInputStream(Source_file)),Out_File,final_output,search_string,stats);

          }

        }

       catch(Exception e){
       System.out.println(e);
       e.printStackTrace();
      }

      }

      /********* Reads the Input Files and Searches for the String ******************************/

      public void searchString(Thread runner,String Source_File,BufferedInputStream in,File output_file,File final_output,String search,String stats)
      {
        int count = 0;   
        int countw = 0; 
        int countl=0;
        String s;
        String[] str;
        String newLine = System.getProperty("line.separator");

        try
        {

            BufferedReader br2 = new BufferedReader(new InputStreamReader(in));
            //OutputFile outfile = new OutputFile();  
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(output_file,true));
            Buffer Buf = new Buffer();
            //StringBuffer sb = new StringBuffer();
            StringBuffer sb1 = new StringBuffer();

                  while((s = br2.readLine()) != null )
                 {
                    str = s.split(search);
                    count = str.length-1;
                    countw += count;
                    if(s.contains(search)){
                       countl++;
                       sb.append(s);
                       sb.append(newLine);
                    }
                    if(countl%100==0)
                    { System.out.println("inside count");
                        Buf.setBuffers(sb.toString());
                        sb.delete(0,sb.length());
                        System.out.println("outside notify");
                        synchronized(runner) 
                        { 
                           runner.notify(); 
                        } 

                        //outfile.WriteFile(sb,bufferedWriter);   
                        //sb.delete(0,sb.length());
                    }
                 }
            }


                        synchronized(runner) 
            { 
               runner.notify(); 
            } 

            br2.close();
            in.close();

            if(countw == 0)
            {
                System.out.println("Input File : "+Source_File );
                System.out.println("Word not found");
                System.exit(0);
            } 
            else
            {
                System.out.println("Input File : "+Source_File );
                System.out.println("Matched word count : "+countw );
                System.out.println("Lines with Search String : "+countl);
                System.out.println("Output File : "+output_file.toString());
                System.out.println();
                        } 
        }
        catch(Exception e){
            System.out.println(e);
            e.printStackTrace();
        }
     } 


 }

2 个答案:

答案 0 :(得分:5)

以下是我将使用的方法:

  • 将队列添加到输出线程。确保访问同步。
  • 将一个方法添加到接受addWork的输出线程(例如String)并将其添加到输出队列。
  • 让输出线程的run方法不断将String出列,并将它们写入文件。
  • 让其他线程通过调用StringaddWork(String)传递给输出线程。

答案 1 :(得分:1)

将stringbuffer作为参数传递给两者。

每次访问stringbuffer时,请确保在同步块中执行此操作

synchronized(myStringBuffer) {
    myStringBuffer.append("Awesome text");
}

synchronized(myStringBuffer) {
    myFileOutput.writeln(myStringBuffer.toString());
}
上面的例子。