volatile关键字无法停止Java中的循环

时间:2019-02-25 14:46:04

标签: java multithreading volatile

def add_event_ent(matcher, doc, i, matches):
    match_id, start, end = matches[i]
    match_doc = doc[start:end]
    for entity in match_doc.ents:
        # k.label = neg_hash <-- says "  attribute 'label' of 'spacy.tokens.span.Span' objects is not writable"

        span = Span(doc, entity.start, entity.end, label=false_alarm_hash)
        doc.ents = list(doc.ents) + [span]  # add span to doc.ents


    ValueError: [E098] Trying to set conflicting doc.ents: '(14, 16, 
    'FRAUD')' and '(14, 16, 'FALSE_ALARM')'. A token can only be part of one entity, so make sure the entities you're setting don't overlap.

运行此代码后,程序不会停止,这很明显,因为线程将准备好的变量备份到自己进程的内存中。当我使用volatile关键字修改阅读内容

public class VolatileOne {
    private static boolean ready ;
    private static int number ;

    private static class ReaderThread extends Thread{
        @Override
        public void run() {
            while (!ready){
                Thread.yield();
            }
            System.out.print(number);
        }
    }

    public static void main(String[] args) {
        new ReaderThread().run();
        ready = true;
        number = 50;
    }
}

此时,读取的变量不会被复制到过程存储器中。但是程序无法停止。什么原因?它与static关键字相关吗?

如果您希望程序输出50并返回,该怎么办?

1 个答案:

答案 0 :(得分:4)

  1. 您需要调用start才能在另一个线程中执行代码。检查thisrunstart之间的区别。

  2. 致电join等待ReaderThread完成。

  3. volatile关键字可以在写入线程和读取线程之间建立happens-before关系,您可以将number = 50;放在ready = true;之前,以确保读者可以通知number50时通知readytrue

示例:

Thread reader = new ReaderThread();
reader.start();
number = 50;
ready = true;
reader.join();