gpt4 book ai didi

Java 同步(对象锁定)未按预期工作

转载 作者:行者123 更新时间:2023-12-01 22:18:50 26 4
gpt4 key购买 nike

请考虑以下代码。

import static java.lang.System.out;

public class Task
{
public Integer k = new Integer(10) ;

public Task()
{
out.println(k + " constructor of Task : " + Thread.currentThread().getName());
}
}
<小时/>
import static java.lang.System.out;

public class Executor2 implements Runnable
{
private Task task;
public Executor2(Task t)
{
out.println("constructor of Executor2 : " + Thread.currentThread().getName());
task = t;
}

@Override
public void run()
{
synchronized(task.k)
{
task.k = 88;
out.println("changed value of task.k to : " + task.k + " " + Thread.currentThread().getName());
try
{
out.println("sleeping");
Thread.sleep(5000);
}
catch (InterruptedException ex)
{
ex.printStackTrace(out);
}
out.println("done");
}
}
}
<小时/>
import static java.lang.System.out;

public class Executor3 implements Runnable
{
private Task task;
public Executor3(Task t)
{
out.println("constructor of Executor3 : " + Thread.currentThread().getName());
task = t;
}

@Override
public void run()
{
synchronized(task.k)
{
task.k = 888;
out.println("changed value of task.k to : " + task.k + " " + Thread.currentThread().getName());
}
}
}
------------------------------------------------------------
public class Main
{
public static void main(String[] args)
{
Task task = new Task();

Executor2 executor2 = new Executor2(task);
Thread thread2 = new Thread(executor2);
thread2.start();

Executor3 executor3 = new Executor3(task);
Thread thread3 = new Thread(executor3);
thread3.start();
}
}

下面是程序的输出。

10 任务构造函数:main
Executor2 的构造函数:main
Executor3 的构造函数:main
将task.k的值更改为:88 Thread-0
sleep
将task.k的值更改为:888 Thread-1
完成

这里令人惊讶的是输出行:将task.k的值更改为:888 Thread-1,预计不会在输出行:done之前打印。为什么 Integer 对象上的锁在 sleep 持续时间过去之前就被释放了?

谢谢。

最佳答案

    synchronized(task.k)
{
task.k = 888;

更改正在同步的对象会破坏同步的意义。然后,您尝试在与旧对象保持同步的同时打印新对象。不要替换线程正在同步的对象!

关于Java 同步(对象锁定)未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30383811/

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