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

标签 java multithreading file

我必须在文件中搜索字符串并将匹配的行写入另一个文件。 我有一个读取文件的线程和一个写入文件的线程。我想将 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();
        }
     } 


 }

最佳答案

这是我会使用的方法:

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

关于java - 在java中的两个线程之间传递字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2874857/

相关文章:

java - 为什么我的二进制数据从网络服务器获取后会变大?

Java 临时文件和自动删除

java - Spring 启动: Json Response is not Mapping to Entity

java - 如果我在同步块(synchronized block)之外的对象上调用 wait 方法会发生什么?

c# - 在 "IsAlive"属性为 false 后,Join 拒绝承认子线程已终止。 C#

c# - 如何立即杀死C#中的Thread

javascript - 对象不支持属性或方法 'delete' ie11 (reactjs)

java - 为什么我不能将整数转换为 double ?

java - 在 Spring 单元测试中将 null 注入(inject)到 Autowiring 的 @Resource 成员

c++ - 标准 C++ 库中的任何地方都使用了 thread::id 吗?