简体   繁体   中英

How to use multiple thread to generate data?

I try to generate data set using multiple threads

I tried to create a Runnable and a couple of Threads in the following

public class DataGenerator {

      static int currentRow = 0 ;
      static PrintWriter pw ;

    public static void main(String[] args) throws FileNotFoundException {
        File file = new File("Test3.csv") ; 
        pw = new PrintWriter(file);
        pw.println("var1,var2,var3") ;    
        Thread t1 = new Thread(new MyRunnable()) ;
    Thread t2 = new Thread(new MyRunnable()) ;
    t1.start(); 
    t2.start();
    t1.join();
    t2.join();

        pw.close();
        System.exit(0) ;
    }


}

class MyRunnable implements Runnable  {
    public void run () {
        for ( int i = DataGenerator.currentRow; i < 50000000; DataGenerator.currentRow ++ ) {
            DataGenerator.pw.println(i + ",19:05.1,some text");
            System.out.println(i);
            }
    }
}

However is looping over o

I cant find out why

Your parent thread is closing the PrintWriter pw before the child Threads t1 and t2 can use it to print. You need to have your parent thread call wait() after you've started your child Threads.

You should review the answer to How to make a Java thread wait for another thread's output? for some help. You can use this information to discover how to solve this issue from a code-standpoint; it's fairly simple.

Note: you have edited your question since this answer was posted; the answer to the following question is even more relevant: Wait until child threads completed : Java

Other useful SO questions with applicable answers that you should read:

See also Java Concurrency Tutorial .

When you start a thread it leaves the thread to start up in its own thread. So what is happening is, its starting the thread and then going straight to the next call pw.close() before the thread has had a chance to start up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM