1

I want to read elements from array and display progress of reading as parallel process reading.

I have two interal classes:

public class NumbersCounter {

    int totalCountOfLines;
    int currentCountOfLines = 1;

    public NumbersCounter() throws FileNotFoundException, IOException {    
        new Read();
        new Progress();
    }

    public static void main(String[] args) {
        try {
            new NumbersCounter();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(NumbersCounter.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(NumbersCounter.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    class Progress extends Thread {  
        public Progress() {
            start();
        }

        @Override
        public void run() {        
            synchronized(new Object()) {
                while (currentCountOfLines <= totalCountOfLines) {
                    System.out.println(currentCountOfLines / totalCountOfLines * 100 + "%");
                    Thread.yield();
                }            
            }
    }}

    class Read extends Thread {
        private FileHandler fh = new FileHandler("ololo.txt");
        private String[] lines;

        public Read() throws FileNotFoundException, IOException {
            this.lines = fh.readFromFile();
            start();
        }

        @Override
        public void run() {

            totalCountOfLines = this.lines.length;

            if (totalCountOfLines > 0) {
                synchronized(new Object()) {
                    for (String line : lines) {
                        currentCountOfLines++;   
                        Thread.yield();
                    }

                }
            } else {
                totalCountOfLines = 0;
            }    
        }
    }
}

When first step of Read Thread is executed, I need to give executing to Progress thread, and then for Read, and then for Progress.

4

2 回答 2

1

使用javax.swing.ProgressMonitorInputStream该类作为输入流的包装器,显示进度对话框。

于 2012-10-21T05:59:08.283 回答
0

请参阅 java.util.concurrent 包的文档。

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/package-summary.html

特别是 ExecutorService、Executor、Callable 和 Future 接口。并发包旨在完成您尝试做的事情,而无需您自己处理锁定和并发。

后台 IO 操作 - 逐步更新 UI。

于 2012-10-20T22:59:26.157 回答