简体   繁体   English

如何使用多线程生成数据?

[英]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 我尝试在下面创建一个Runnable和几个线程

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 但是正在循环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. 在子线程t1t2可以使用它打印之前,您的父线程将关闭PrintWriter pw You need to have your parent thread call wait() after you've started your child Threads. 启动子线程后,需要让父线程调用wait()

You should review the answer to How to make a Java thread wait for another thread's output? 您应该查看如何使Java线程等待另一个线程的输出的答案 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 以下问题的答案更为相关: 等待子线程完成:Java

Other useful SO questions with applicable answers that you should read: 您应该阅读的其他有用的SO问题以及适用的答案:

See also Java Concurrency Tutorial . 另请参见Java并发教程

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. 所以发生的事情是,它启动了线程,然后在线程有机会启动之前直接进入下一个调用pw.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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