2014-12-03 36 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