gpt4 book ai didi

java - 这个同步块(synchronized block)中发生了什么

转载 作者:行者123 更新时间:2023-12-03 12:53:54 25 4
gpt4 key购买 nike

我试图查看 synchronized 之前的变量值是否可以被多个线程修改堵塞。我对以下代码的行为感到困惑。我创建了一个具有 synchronized 的方法像下面这样 block

public void testMethod( String x )
{
String myX = x.toUpperCase();
System.out.println( myX ); // Prints the value before the critical section
synchronized( this )
{
try
{
Thread.sleep( 5000 );
}
catch( InterruptedException e )
{
e.printStackTrace();
}
System.out.println( myX ); // Prints the value inside the critical section
}
}

然后,我创建了两个线程,它们使用两个不同的字符串值调用此方法,如下所示,
Thread myThreadOne = new Thread( () -> testMethod( "T1" ) );
Thread myThreadTwo = new Thread( () -> testMethod( "T2" ) );

并在 main 方法中调用。
public static void main( String[] args )
{
Test t1 = new Test();
t1.myThreadOne.start();
t1.myThreadTwo.start();
}

现在我期待的输出类似于 T1 , T2 , T2 , T2 .或者无论哪个线程最后开始都应该打印 synchronized 之前和内部的值。 block ,因为很明显变量 myX当第一个线程处于 hibernate 状态或第一个线程在临界区内时,将具有来自第二个线程的更新值。

但输出始终是第一个线程值,然后是第二个线程值。点赞 T1 , T2 , T1 , T2 .这是怎么发生的?变量 myXsynchronized 之外 block ,是不是第二个线程修改了这个值。还是我的示例代码有问题?

最佳答案

您需要声明 myx method 之外的变量:

String myX;

public void testMethod( String x )
{
myX = x.toUpperCase();
System.out.println( myX ); // Prints the value before the critical section
synchronized( this )
{
try
{
Thread.sleep( 5000 );
}
catch( InterruptedException e )
{
e.printStackTrace();
}
System.out.println( myX ); // Prints the value inside the critical section
}
}


这将为您提供所需的结果。

为什么 :
  • 局部变量本质上是线程安全的,不被线程共享
  • 而类变量是共享的

  • 你可以看看这个: Why are local variables thread safe in Java

    关于java - 这个同步块(synchronized block)中发生了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62208717/

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