java - 在给定时间后跳到带有线程的 for 循环中的下一个索引

标签 java multithreading for-loop

我正在尝试编写一个从文件 .txt 创建词汇表的程序。它需要一个文件,创建一个文档(一个字符串),将该文档分割成句子,最后,它对每个句子执行一些操作(标记化、词性标记、成分树解析等)。

有时程序会停在一个句子上(这对我来说很糟糕),所以我要做的就是避免在一个句子上停留太久(假设 120 秒)。 如果是这样,程序应该转到列表中的下一句。

我想使用线程和计时器并检查时间是否已过,但我对如何使用线程感到困惑。

这是我的代码的一部分:

public class Vocabulary {
    private Thread thread;
    private long sentenceDuration;
    private Queue<File> corpus;

    public Vocabulary(){
        this.sentenceDuration = 0;           
        corpus = loadCorpus();
    }

    public void buildVocabulary(){

        for (File f : corpus) {
                Scanner in = new Scanner(new FileReader(f.getPath()));

                // Create a string representing the document
                String document = "";
                while (in.hasNextLine()) {
                    document += in.nextLine() + " ";
                }
                in.close();

                // Split the document in sentences
                ArrayList<String> sentences = tpr.documentToSentences(document);

                for (int i = 0; i < sentences.size(); i++) {
                    Timer timer = new Timer(1000, timer());
                    timer.start();

                    while(sentenceDuration < 120){      // while it takes under 120 seconds to compute the sentence, ok.

                        List<CoreLabel> tokens = tpr.tokenize(sentences.get(i));        // tokenize the sentence
                        Tree parse = tpr.apply(tokens);                                 // create the costituents tree
                        Object[] basicDependencies = tpr.getBasicDependencies(parse);   // get the basic dependencies from the tree

                        // some operations here...             

                        Thread.sleep(1000);     // 1000 ms
                    }

                    // when it takes over 120 seconds to compute the sentence, jump to the next sentence 
                    System.out.println("Hey, I took long time to compute the sentence. I'm going to the next one!");
                }  

                // Other operations here...
        }
    }

    public void start() {
        end();
        this.thread = new Thread(this);
        this.thread.start();
    }

    public void end() {
       if (thread != null && thread.isAlive()) {
            thread.interrupt();
        }
    }

    private ActionListener timer() {

        ActionListener taskPerformer = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                sentenceDuration++;
            }
        };
        return taskPerformer
    }   
}

主要我只是简单地调用:

 public static void main(String[] args) {
        new Vocabulary().start();     
 }

如何对程序说:“如果过了120秒,就跳过这句话!”。即“立即退出while循环!无论你在做什么操作”。 ?

谢谢!

最佳答案

好的,那么从信号量开始,一个简单的 join() 就可以了。像这样的东西:

// Split the document in sentences
ArrayList<String> sentences = tpr.documentToSentences(document);

for (int i = 0; i < sentences.size(); i++) {
    SentenceProcessorThread sentenceProcessorThread = new SentenceProcessorThread(sentences.get(i));
    sentenceProcessorThread.start();
    try {
        sentenceProcessorThread.join(120000); // your timeout period goes here
        if (sentenceProcessorThread.isAlive()) {
            sentenceProcessorThread.interrupt();
            System.out.println("aborting thread");
        }
    } catch (InterruptedException x) {
    }
}

将句子处理逻辑放入它自己的线程中:

class SentenceProcessorThread extends Thread {
    private String sentence;

    public SentenceProcessorThread(String sentence) {
        this.sentence = sentence;
    }

    public void run() {
        try {
            // your sentence processing logic goes here
        } catch (InterruptedException x) {
        }
    }
}

关于java - 在给定时间后跳到带有线程的 for 循环中的下一个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38724064/

相关文章:

java - 如何设置 Libgdx 位图字体大小?

c++ - #pragma omp parallel 和 #pragma omp parallel for 之间的区别

c++ - 错误: 'QObject' 是 'SerialPort' QObject::connect(&uartObj, SIGNAL(readDone(QByteArray)), this, SLOT(hdlRxDone(QByteArray))) 的模糊基数;

Java 打印线程卡住 : WHY?

Swift for 循环 "Expression type ' [[String : String]]' is ambiguous without more context

java - 什么是容器类?

java - java swt表中的动态组合框列表

java - sdkman gradle 3.4无法确定java版本

r - 在了解R循环错误: unexpected '}' in “}” 方面需要帮助

C++:将 vector 中的项目存储到 map 中