gpt4 book ai didi

Java线程: Please clarify this understanding

转载 作者:行者123 更新时间:2023-12-02 14:38:56 29 4
gpt4 key购买 nike

public class Qn {

static class Friend {
private final String name;

public Friend(String name) {
this.name = name;
}

public String getName() {
return this.name;
}

// recipient - the person who greets
public synchronized void sayHi(Friend recipient) {
System.out.format("%s" + " said hi to %s %n",
this.name, recipient.getName());
}
}

public static void main(String[] args) {
final Friend john = new Friend("John");
final Friend peter = new Friend("Peter");

new Thread(new Runnable() {
public void run() {
john.sayHi(peter);
}
}, "thread1").start();
}
}

问题:

如果理解正确,请澄清以下内容

  1. 当调用john.sayHi()时,线程thread1已获取内在锁定 john 对象,以便访问 john 对象的 sayHi() 方法。

  2. 线程thread1在JVM中独立运行。

我在网上看到这些说法,不知道他们的意思! 【线程怎么可以运行在对象上!!!事实上线程执行代码,对吗?]

  • 线程 thread1 未在 JVM 内的任何其他对象上运行。

  • 线程永远不会在任何对象上运行。线程永远不会由对象执行。一个线程永远不会在任何其他线程上运行。线程总是直接在 JVM 中运行。

  • 最佳答案

    When invoking john.sayHi(), the Thread thread1 has acquired intrinsic lock of john object in-order to access the sayHi() method of john object.

    更准确地说:

    当调用john.sayHi()时,线程thread1将等待,直到它可以获取john上的锁,然后再执行说嗨。一旦获得锁,它将执行sayHi。当方法退出时,它将释放锁。

    The Thread thread1 is running independently in JVM.

    独立于什么?其他线程?是的,直到它尝试获取锁。此时,它可能会受到其他线程的阻碍。当它有锁时,它可以阻止其他线程。

    The thread thread1 is not running on any other object inside the JVM.

    线程在 CPU 上运行,而不是在对象上运行。

    你是问一个线程是否可以并行执行多个方法?如果是这样,答案是否定的。

    A thread never runs on any object.

    线程在 CPU 上运行,而不是在对象上运行。

    A thread is never executed by an object.

    线程不由任何东西执行。线程执行代码。

    A thread never runs on any other thread.

    线程在CPU上运行,而不是线程。

    A thread always run directly in JVM.

    JVM 有一个虚拟 CPU,线程在该虚拟 CPU 上运行。

    关于Java线程: Please clarify this understanding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23414744/

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