在使用多线程应用程序创建WriteFiles时遇到问题

时间:2017-03-06 19:37:43

标签: java multithreading multidimensional-array bufferedwriter thread-synchronization

我在尝试创建一个线程构造函数时会遇到一些问题,该构造函数将接受文件名和要写入文件的二维数据数组。线程运行方法假设将该二维数组写入该文件,然后为courses.txt文件和students.txt文件实例化该线程。我试图通过使用多线程应用程序来做到这一点。 2D数组将是一个2D String数组,正如我已经在代码上创建的那样。我已经将数据硬编码到2D String数组中,但我对如何将该数组和文件名传递给将写入该文件的线程感到困惑。我知道我可以使用一个run()方法编写一个线程类,该方法将写入任一文件。如何在WriteFiles.java的main()中创建该线程的两个实例,然后传递一个Student数据并传递另一个Course数据?

这是我到目前为止的代码,并且非常喜欢一些指导:

import java.util.*;
import java.io.*;

class WriteFiles implements Runnable
{

  static final String FILE = "courses.txt";
  static final String FILE2 = "students.txt";
  BufferedWriter bw;
  Thread thread[] = new Thread[2];
  private String studentList[][];
  private String courseList[][];


  public WriteFiles()
  {
    try
    {
      bw = new BufferedWriter( new FileWriter( FILE ) );
      bw = new BufferedWriter( new FileWriter( FILE2 ) );
    }
    catch( FileNotFoundException fnfe )
    {
      System.out.println( fnfe );
      System.exit( 1 );
    }
    catch( IOException ioe )
    {
      System.out.println( ioe );
      System.exit( 2 );
    }

  }


  public void writeFile( String str )
  {

    try{
      bw.write( str );
    } catch( IOException ioe ){
      System.out.println( ioe );
    }
  }



  public void run()
  {

        String studentList[][] =  {
            {"Python","INSY 3300","530-650 MW","1,3"},
            {"Networking","INSY 3303","530-650 TR","1,3"},
            {"DBMS","INSY 3304","900-950 MWF","1,3"},
            {"Analysis&Design","INSY 3305","700-820 TR","1,3"},
            {"Java I","INSY 4305","700-820 TR","1,3"},
            {"Java II","INSY 4306","530-650 TR","1,3"},
            {"Mobile App","INSY 4308","200-320 TR","1,3"},
            {"Web Development","INSY 4315","1000-1050 MWF","1,3"},
            {"Resource Management","INSY 4325","100-220 TR","1,3"}
                                 };

        String courseList[][] =  {
            {"US","NONRESIDENT","123456","Jones","123 Cooper St","Arlington","Texas","76019","12345"},
            {"INT","ACTIVE","A-654789","Degrassey","18 Love Lane","Dallas","Texas","75052","67123"},
            {"INT","INACTIVE","A-543891","Franco","1201 Trail Road","Euless","Texas","74032","19814"},
            {"US","RESIDENT","345123","Hughes","1803 Division","Fort Worth","Texas","76034","674532"},
            {"US","RESIDENT","988776","Cooper","111 Marsh Lane","Bedford","Texas","76111","90906"},
            {"INT","INACTIVE","B-577463","Patel","2218 Border St","Arlington","Texas","76015","81832"}
                                 };



  }

  public void writeCourses()
  {
for (Student s:studentList){

            System.out.print(s.toString());
        }
  }

   public void writeStudents()
  {
       for (Course c:courseList){

           System.out.print(c.toString());
        }  

  }


  public static void main( String arg[] )
  {
    WriteFiles myTread = new WriteFiles();
    myTread.writeCourses();
    myTread.writeStudents();
  }
}

最终的students.txt输出假设看起来像这样;按数据分割:

US; NONRESIDENT; 123456; Jones; 123 Cooper St; Arlington; Texas; 76019; 12345 INT; ACTIVE; A-654789; Degrassey; 18 Love Lane; Dallas; Texas; 75052; 67123 INT; INACTIVE; A-543891; Franco; 1201 Trail Road; Euless; Texas; 74032; 19814 US; RESIDENT; 345123; Hughes; 1803 Division; Fort Worth; Texas; 76034; 674532 US; RESIDENT; 988776; Cooper; 111 Marsh Lane; Bedford; Texas; 76111; 90906 INT; INACTIVE; B-577463; Patel; 2218 Border St; Arlington; Texas; 76015; 81832

最终的course.txt输出假设看起来像这样;按数据分割:

Python; INSY 3300; 530-650 MW; 1; 3 网络; INSY 3303; 530-650 TR; 1; 3 DBMS; INSY 3304; 900-950 MWF; 1; 3 分析与设计; INSY 3305; 700-820 TR; 1; 3 Java I; INSY 4305; 700-820 TR; 1; 3 Java II; INSY 4306; 530-650 TR; 1; 3 移动应用; INSY 4308; 200-320 TR; 1; 3 Web开发; INSY 4315; 1000-1050 MWF; 1; 3 资源管理; INSY 4325; 100-220 TR; 1; 3

我没有问题让这个方法工作成功,但是我现在正在尝试使用多线程应用程序的不同方法。这是一个没有线程的工作输出:

import java.util.*;
import java.io.*;

public class WriteFiles {
    private static Formatter output;
    private static Scanner input;

    public static void main(String[] args) {

        ArrayList<Student> studentList = new ArrayList<Student>();
        writeTextFile1();

         for (Student s:studentList){

            System.out.print(s.toString());
        }
        ArrayList<Course> courseList = new ArrayList<Course>();
        writeTextFile();

        for (Course c:courseList){

           System.out.print(c.toString());
        }
    }

    public static void writeTextFile(){
        try{
            output = new Formatter("courses.txt");
            output.format("%s;%s;%s;%d;%d%n","Python","INSY 3300","530-650 MW",1,3);
            output.format("%s;%s;%s;%d;%d%n","Networking","INSY 3303","530-650 TR",1,3);
            output.format("%s;%s;%s;%d;%d%n","DBMS","INSY 3304","900-950 MWF",1,3);
            output.format("%s;%s;%s;%d;%d%n","Analysis&Design","INSY 3305","700-820 TR",1,3);
            output.format("%s;%s;%s;%d;%d%n","Java I","INSY 4305","700-820 TR",1,3);
            output.format("%s;%s;%s;%d;%d%n","Java II","INSY 4306","530-650 TR",1,3);
            output.format("%s;%s;%s;%d;%d%n","Mobile App","INSY 4308","200-320 TR",1,3);
            output.format("%s;%s;%s;%d;%d%n","Web Development","INSY 4315","1000-1050 MWF",1,3);
            output.format("%s;%s;%s;%d;%d%n","Resource Management","INSY 4325","100-220 TR",1,3);
            output.close();
        }
        catch(IOException ioe){
        ioe.printStackTrace();
        }
    }

    public static void writeTextFile1(){

        try{
            output = new Formatter("students.txt");
            output.format("%s;%s;%s;%s;%s;%s;%s;%d;%d%n","US","NONRESIDENT","123456","Jones","123 Cooper St","Arlington","Texas",76019,12345);
            output.format("%s;%s;%s;%s;%s;%s;%s;%d;%d%n","INT","ACTIVE","A-654789","Degrassey","18 Love Lane","Dallas","Texas",75052,67123);
            output.format("%s;%s;%s;%s;%s;%s;%s;%d;%d%n","INT","INACTIVE","A-543891","Franco","1201 Trail Road","Euless","Texas",74032,19814);
            output.format("%s;%s;%s;%s;%s;%s;%s;%d;%d%n","US","RESIDENT","345123","Hughes","1803 Division","Fort Worth","Texas",76034,674532);
            output.format("%s;%s;%s;%s;%s;%s;%s;%d;%d%n","US","RESIDENT","988776","Cooper","111 Marsh Lane","Bedford","Texas",76111,90906);
            output.format("%s;%s;%s;%s;%s;%s;%s;%d;%d%n","INT","INACTIVE","B-577463","Patel","2218 Border St","Arlington","Texas",76015,81832);
            output.close();
        }
        catch(IOException ioe){
        ioe.printStackTrace();
        }
    }
}

3 个答案:

答案 0 :(得分:0)

  

我对如何将该数组和文件名传递给将写入文件的线程感到有点困惑

除非我不理解这个问题,否则简短的回答是关于构造函数的参数。您可以为String[][]传递内容,并输入String作为输出文件名。

public class WriteFile implements Runnable {
   private final String[][] contentLines;
   private final String outputFilename;
   public WriteFile(String[][] contentLines, String outputFilename) {
      this.contentLines = contentLines;
      this.outputFilename = outputFilename;
   }
   public void run() {
      // write the content to the file-name
      BufferedWriter bw = new BufferedWriter(new FileWriter(outputFilename));
      try {
         for (String[] contentLine : contentLines) {
            ...
         }
      } finally {
         bw.close();
      }
   }
}

然后你会这样说:

Thread studentThread = new Thread(new WriteFile(studentList, "students.txt"));
studentThread.start();
Thread courseThread = new Thread(new WriteFile(courseList, "courses.txt"));
courseThread.start();
// now wait for the threads to finish writing
studentThread.join();
courseThread.join();

如果要将StudentCourse个对象传入此runnable,则需要创建一个不同的runnable来处理正在编写的每种类型的数据。

// student file writer runnable
Thread studentThread = new Thread(new WriteStudentFile(studentList, "students.txt"));
// course file writer runnable
Thread courseThread = new Thread(new WriteCourseFile(courseList, "courses.txt"));

答案 1 :(得分:0)

我刚刚发现我的arraylist都错了。我要将它全部视为一条线,但在我的GUI程序中仍然是2D bc我要分割它;术语

    String studentList[][] =  {
        {"Python;INSY 3300;530-650 MW;1,3"},
        {"Networking;INSY 3303;530-650 TR;1,3"},
        {"DBMS;INSY 3304;900-950 MWF;1,3"},
        {"Analysis&Design;INSY 3305;700-820 TR;1,3"},
        {"Java I;INSY 4305","700-820 TR","1,3"},
        {"Java II","INSY 4306;530-650 TR;1,3"},
        {"Mobile App;INSY 4308;200-320 TR;1,3"},
        {"Web Development;INSY 4315;1000-1050 MWF;1,3"},
        {"Resource Management;INSY 4325;100-220 TR;1,3"}
                             };

    String courseList[][] =  {
        {"US;NONRESIDENT;23456;Jones;123 Cooper St;Arlington;Texas;76019;12345"},
        {"INT;ACTIVE;A-654789;Degrassey;18 Love Lane;Dallas;Texas;75052;67123"},
        {"INT;INACTIVE;A-543891;Franco;1201 Trail Road;Euless;Texas;74032;19814"},
        {"US;RESIDENT;345123;Hughes;1803 Division;Fort Worth;Texas;76034;674532"},
        {"US;RESIDENT;988776;Cooper;111 Marsh Lane;Bedford;Texas;76111;90906"},
        {"INT;INACTIVE;B-577463;Patel;2218 Border St;Arlington;Texas;76015;81832"}
                             };

我还是有点困惑。我在主编写线程数组吗?

答案 2 :(得分:0)

解决了!对于那些想要引用的人,如果碰巧遇到类似的问题,我将分享代码:

//Donovan
package hw2;
//Importing Java imports that are required for the program to execute properly
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.*;
import java.io.*;
//Creating my public & private class for WriteFiles that uses Runnable, including Formatter 
public class WriteFiles implements Runnable{
private String threadDonovan;
private String[][] arrayDonovan;
Formatter output;
//Creating a WriteFiles which will accept a thread as a String and a 2D ArrayList for later Execution
public WriteFiles(String str, String arrays[][])
{
//Create a string an array for later use in the run()
threadDonovan = str;
arrayDonovan = arrays;
}
//Time to run a try and catch methods
public void run()  
    {
        //First have to try a few things
        try
            {
                //create a Formatter from my Thread
                output = new Formatter(threadDonovan);
                //Running 2 for loops to output the correct information into the .txt files
                for (int i = 0; i < arrayDonovan.length; i++)
                    {
                        for (int j = 0; j < arrayDonovan[i].length; j++)
                            {
                                //Proper Formatting is Required so the .txt files
                                //are written properly so they're the same way as HW1
                                //and so the GUI doesn't run into any problems
                                output.format("%s%n",arrayDonovan[i][j]);
                            }
                    }
                //Once the Data is written, have to close the Formatter                  
                output.close();           
            }  
        //Now have to catch a few errors and print them to debug if needed
        catch( IOException ioe )
            {
                ioe.printStackTrace();
                System.out.println(ioe);
                System.exit(2);
            }
}
//creating the main which will have the 2D ArrayList and the Executor Service
public static void main(String[] args) throws InterruptedException
    {
    //create my 2D ArrayList for Students
    String studentList[][] = {
              {"US;NONRESIDENT;23456;Jones;123 Cooper St;Arlington;Texas;76019;12345"},
              {"INT;ACTIVE;A-654789;Degrassey;18 Love Lane;Dallas;Texas;75052;67123"},
              {"INT;INACTIVE;A-543891;Franco;1201 Trail Road;Euless;Texas;74032;19814"},
              {"US;RESIDENT;345123;Hughes;1803 Division;Fort Worth;Texas;76034;674532"},
              {"US;RESIDENT;988776;Cooper;111 Marsh Lane;Bedford;Texas;76111;90906"},
              {"INT;INACTIVE;B-577463;Patel;2218 Border St;Arlington;Texas;76015;81832"}
                              };
    //create my 2D ArrayList for Courses
    String courseList[][] = {
              {"Python;INSY 3300;530-650 MW;1;3"},
              {"Networking;INSY 3303;530-650 TR;1;3"},
              {"DBMS;INSY 3304;900-950 MWF;1;3"},
              {"Analysis&Design;INSY 3305;700-820 TR;1;3"},
              {"Java I;INSY 4305;700-820 TR;1;3"},
              {"Java II;INSY 4306;530-650 TR;1;3"},
              {"Mobile App;INSY 4308;200-320 TR;1;3"},
              {"Web Development;INSY 4315;1000-1050 MWF;1;3"},
              {"Resource Management;INSY 4325;100-220 TR;1;3"}
                            };
    //What will be created once ExecutorService Starts for Students
    WriteFiles studentFile = new WriteFiles("students.txt",studentList);
    //What will be created once ExecutorService Starts for Courses
    WriteFiles courseFile = new WriteFiles("courses.txt",courseList);
    //Begin the Executor Service
    ExecutorService executorService = Executors.newCachedThreadPool();
    //start the first Task/Thread to create students.txt from the studentList 2D ArrayLIst        
    executorService.execute(studentFile);
    //start the first Task/Thread to create courses.txt from the courseList 2D ArrayLIst  
    executorService.execute(courseFile); //start task 2
    //End the Executor Service
    executorService.shutdown();
    }
}