gpt4 book ai didi

java - java程序的线程内语义

转载 作者:行者123 更新时间:2023-11-29 05:18:03 26 4
gpt4 key购买 nike

下面的代码是否违反线程内语义?

static Integer sync;

public static void main(String[] args) throws Exception {
Runnable r = new Runnable() {

@Override
public void run() {
sync = 6;
System.out.println("written thread 1");
try {
Thread.sleep(9999);
} catch (InterruptedException ex) {
Logger.getLogger(IO.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(sync);
}

};
Runnable t = new Runnable() {
@Override
public void run() {
sync = 2;
System.out.println("written thread 2");
try {
Thread.sleep(9999);
} catch (InterruptedException ex) {
Logger.getLogger(IO.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(sync);
}
};

Thread th1 = new Thread(r);
Thread th2 = new Thread(t);
th1.start();
th2.start();
}

DEMO

结果是:

written thread 1
written thread 2
2
2 //!!!! Is intra-thread semantic violates?

17.4 中的 JLS 说:

[...]As previously mentioned, all threads need to obey the correct intra-thread semantics for Java programs.[...]

我认为线程内语义意味着线程将像程序中的单个线程一样工作。即,th1 赋值仅对 th1 有效,对 th2 类似。

我可能没有正确理解线程内语义概念吗?

最佳答案

问题是,你自己和“线程间” Action 在这里

An inter-thread action is an action performed by one thread that can be detected or directly influenced by another thread.

不是“线程内” Action 。两个线程共享一个公共(public)内存位置(变量 sync),设置一个线程的值是一种效果,可以被另一个线程检测到。 “线程内”语义的描述说

The actions of each thread in isolation must behave as governed by the semantics of that thread, with the exception that the values seen by each read are determined by the memory model.

(强调我的,source)

关于java - java程序的线程内语义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25824604/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com