2014-12-03 32 views
2

我正在处理一个巨大的数据文件,并将其作为“在下面张贴”,并在单独的线程中读取它。而在主线程中,我想检索一些数据frm文件,如logFile.getFileHash.getTimeStamp,以在该timeStamp上执行一些操作。我面临的问题是,只有当我的文件在其他线程中完全读取时,如何开始从主线程的文件中读取一些数据?如何从正在工作线程上读取的文件读取主线程上的数据

注意:我不想对读取文件的同一线程上的文件检索到的数据执行操作,我想在主线程上执行此操作。

例如

public static void main(String[] args) throws IOException { 

//fileThread.start(); will take 8 seconds. 
/* 
*here i want to read some data from my file to perform some processing but only 
*when the thread that handles reading the file finishes work. 
} 

文件

private static void processFile(File dataFile) throws IOException { 
    // TODO Auto-generated method stub 
    MeasurementFile logfile = new MeasurementFile(dataFile); 
    System.out.println(logfile.getTotalLines()); 
    System.out.println(logfile.getFileHash().get(logfile.getTotalLines()).getFullParameters().length); 
    System.out.println(logfile.getFileHash().get(logfile.getTotalLines()).getEngineSpeed()); 
} 

回答

1

Thread.join能适应这一点。

public static void main(String[] args) throws IOException { 

fileThread.start(); 
fileThread.join(); 
//..now this thread blocks until *fileThread* exits 

} 
+0

只有在读取文件后工作线程结束时,这才起作用。如果它应该做一些其他的工作,那么它不是最好的匹配。 – ciamej 2014-12-03 11:09:39

-1

在文件线程中添加一个属性并为其添加一个公共getter。当该线程完成时,将isFinished的值更改为true;

private boolean finished = false; 
public isFinished(){...} 

在你的主线程,只是睡了吧,恢复它来检查文件线程完成:

public static void main(String[] args) throws IOException { 
    ... 
    fileThread.start(); 
    ... 
    while(!fileThread.isFinished()){ 
     try{ 
      Thread.sleep(1000);//1 second or whatever you want 
     }catch(Exception e){} 
    } 
    //Do something 
    .... 
} 
+0

'finished'应该至少不稳定。这不是线程安全的 – ciamej 2014-12-03 11:07:45

+0

错误。易失性用于指示变量的值将由不同的线程修改,而不是由于主线程只会读取它。 这个解决方案是完全线程安全的,事实上,你只是与一个只由其中一个修改的变量通信线程。 – codependent 2014-12-03 11:33:47

+0

不是。我们在这里是读取变量的主线程和修改它的文件线程。如果有两个线程访问一个变量(即使只有一个变量写入它),那么该变量必须是易失性的。这是Java内存模型所要求的。否则(没有volatile),jvm可以自由缓存非易失性变量的值,并且永远不会让主线程观察由不同线程写入的任何值。 – ciamej 2014-12-03 17:05:05

0

我不知道我理解的问题,但我认为你正在尝试在子线程完成读取而不结束子线程之后,让主线程读取同一文件。如果是这样,那么你可以创建一个同步的readMyFile(File file)方法,任何线程都可以使用它来读取任何文件,当然要确保子线程首先读取文件。

+0

谢谢你的回答,我想我需要做一些像同步一样的东西。鉴于上面的代码你请告诉我如何使用同步? – rmaik 2014-12-04 12:34:31

0

对不起,延迟回复。

如果我认为是正确的,那么你可以做这样的事情,大致...

public static void main(String args[]) { 

    ... 
    fileThread.start(); 

    synchronized (fileThread) { 
     try{ 
      fileThread.wait(); 
     }catch(InterruptedException e){ 
      e.printStackTrace(); 
     } 
    } 
    ... 
    MyReader.readMyFile(file); 
    ... 
} 

...而fileThread线程类的东西作为...

class FileThread extends Thread { 

public void run() { 

    synchronized (this){ 
     ... 
     MyReader.readMyFile(file); 
     notify(); 
     ... 
    } 
} 

这是一种方式。我希望它有帮助。

+0

谢谢你的答案。你会提供一些解释它是如何工作的,以及主线程和文件线程是如何同步的? – rmaik 2014-12-11 08:29:36