java - java程序的线程内语义

标签 java multithreading

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

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/

相关文章:

c++ - 我如何在 C++11 中实现类似 "interrupted exception"行为的 Java

java - 空白的 Java Swing 框架

java - 为特定的 JTable 单元格设置鼠标光标

java - 如何从具有多个相同字段值的类的值中获取字段名称

java - 如何在 android 的 ListView 中获取项目的 View ?

c++ - 如何为 MFC 线程设置超时

multithreading - ReSTLet客户端句柄Web服务关闭

java - OpenCV - 在 Java 中改变相机分辨率

java - 使用 jar 库自动部署应用程序

java - 等待线程是否重新访问同步方法中的代码