【问题标题】:Should threadMessage in the SimpleThreads example be synchronized?SimpleThreads 示例中的 threadMessage 是否应该同步?
【发布时间】:2014-11-14 14:50:20
【问题描述】:

SimpleThreads example中的threadMessage方法原则上应该是synchronized吗?

【问题讨论】:

    标签: java multithreading static thread-safety


    【解决方案1】:

    假设你的意思是this code:

    // Display a message, preceded by
    // the name of the current thread
    static void threadMessage(String message) {
        String threadName =
            Thread.currentThread().getName();
        System.out.format("%s: %s%n",
                          threadName,
                          message);
    }
    

    我的回答是否定的,没有要保护的共享状态,因此不需要进一步锁定(在被调用的事物中已经完成的操作)。

    获取 currentThread 已经完成了它需要的任何锁定(如果有的话)。 format 方法将格式化的字符串写入标准输出,PrintStream 会在标准输出中进行锁定以确保写入的消息不会混杂在一起,并且每一行都是单独写入的。

    将线程名称存储在局部变量 threadName 意味着它在自己的堆栈帧上拥有自己的存储空间(分配给该特定方法调用),局部变量内容不能被任何其他调用此方法的内容覆盖(由另一个线程或同一线程)。如果 threadName 是一个静态变量,那么您需要进行同步,这样它就不会在调用 currentThread 方法和 format 方法之间被覆盖。将变量设置为 local 让事情变得简单。

    如果多个线程同时调用此方法,则不会发生任何事情,除非条目可以在标准输出中以不同的顺序显示。无论如何都有可能发生。

    【讨论】:

      猜你喜欢
      • 2016-11-04
      • 1970-01-01
      • 2014-03-20
      • 1970-01-01
      • 2013-02-02
      相关资源
      最近更新 更多