join() 是如何工作的? (Java中的多线程)

发布于 2024-10-16 06:54:18 字数 1260 浏览 4 评论 0原文

我正在准备考试,在完成了一些示例练习(其中包含正确答案)后,我根本无法理解它们。

问题

(多项选择):以下计划可能产生哪些结果?

一个) 值为 1。 值为 1。 最终值为 1。B

) 值为 1。 值为 1。 最终值为2。C

) 值为 1。 最终值为1。 值为 2。D

) 值为 1。 最终值为2。 值为 2。

程序

public class Thread2 extends Thread {

    static int value = 0;
    static Object mySyncObject = new Object();

    void increment() {

        int tmp = value + 1;
        value = tmp;

    }

    public void run() {

        synchronized(mySyncObject) {

            increment();
            System.out.print("Value is " + value);

        }

    }

    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread2();
        Thread t2 = new Thread2();

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.print("Final value is " + value);

    }

}

正确答案是:A)、C) 和 D)。

对于情况A)我不明白两个线程(在同步块内增加一个看似静态的变量之后(!))最终如何可能被设置为1并且最终值也是1......?

情况 C 和 D 同样让我感到困惑,因为我真的不明白 main() 怎么可能在两个必需的线程(t1 和 t2)完成之前完成。我的意思是,它们的 join() 方法是从 main 函数内部调用的,所以据我了解, main 函数应该需要等待 t1 和 t2 都使用它们的 run() 方法完成(从而打印它们的值) ...??

如果有人能指导我完成这个任务那就太好了。

预先感谢,非常感谢! 芥末

I'm preparing for an exam and after going over some sample exercises (which have the correct answers included), I simply cannot make any sense out of them.

The question

(Multiple Choice): What are the some of the possible outcomes for the program below?

A)
Value is 1.
Value is 1.
Final value is 1.

B)
Value is 1.
Value is 1.
Final value is 2.

C)
Value is 1.
Final value is 1.
Value is 2.

D)
Value is 1.
Final value is 2.
Value is 2.

The Program

public class Thread2 extends Thread {

    static int value = 0;
    static Object mySyncObject = new Object();

    void increment() {

        int tmp = value + 1;
        value = tmp;

    }

    public void run() {

        synchronized(mySyncObject) {

            increment();
            System.out.print("Value is " + value);

        }

    }

    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread2();
        Thread t2 = new Thread2();

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.print("Final value is " + value);

    }

}

The correct answers are: A), C) and D).

For case A) I don't understand how it's possible that both threads (after incrementing a seemingly static variable from within a synchronized block(!)) end up being set to 1 and the final value is thus 1 as well...?

Case C and D are equally confusing to me because I really don't understand how it's possible that main() finishes before both of the required threads (t1 and t2) do. I mean, their join() methods have been called from within the main function, so to my understanding the main function should be required to wait until both t1 and t2 are done with their run() method (and thus have their values printed)...??

It'd be awesome if someone could guide me through this.

Thanks in advance, much appreciated!
wasabi

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

伴我心暖 2024-10-23 06:54:18

答案或问题有问题。

您对 join() 的理解是正确的。在两个线程都完成之前,无法打印“最终值为”消息。对 join() 的调用确保了这一点。

此外,increment() 方法只能从静态字段上的同步块内调用。所以这个方法不可能被两个线程同时调用。 “Value is”输出也在同一同步块内。因此,除了同步块内之外,无法从任何地方访问 value 属性。因此,这些操作是线程安全的。

该程序唯一可能的输出是“值是 1。值是 2。最终值是 2”。 (实际上,输出之间没有句点或空格 - 我只是匹配答案的格式。)

我无法解释为什么这与任何答案都不匹配,除了写问题的人搞砸了一些事情。

There is something wrong with the answers or the question.

Your understanding of join() is correct. The "Final value is" message cannot be printed until both threads have completed. The calls to join() ensures this.

Furthermore, the increment() method is only called from within a synchronized block keyed on a static field. So there's no way this method could be called simultaneously by two threads. The "Value is" output is also within the same synchronized block. So there's no access to the value property from anywhere except within the synchronized block. Therefore, these operations are thread-safe.

The only possible output from this program is "Value is 1. Value is 2. Final value is 2." (In reality, there are no periods or spaces between the outputs - I'm just matching the format of the answers.)

I cannot explain why this matches none of the answers except that whoever wrote the question messed something up.

離人涙 2024-10-23 06:54:18

首先我同意 rlibby 的观点。他的答案可以通过编写程序并将输出呈现给老师来证明。
如果我们忽略这个,看看这个:

  • 它保证有两次“Value is...”打印,
  • 不可能两次打印“Value is 1”,因为增量是由静态对象同步的(这消除了 A 和 B),
  • 打印语句的顺序不能可以预测,
  • 但是:如果我们读到“最终值为 x”,则也必须有一个“值为 X”,无论是之前还是之后,但它必须存在
  • First i'd like to agree with rlibby. His answer can be proven by writing the program an present the output to the teacher.
    If we omit that look at this:

  • its guaranteed to have two prints of 'Value is...'
  • it's not possible to print 'Value is 1' twice, since the increment is synchronized by a static object (this eliminates A and B)
  • the order of the print statements can not be forecasted
  • but: if we read a 'Final value is x' there must be a 'Value is X' too, no matter if before or after but it must exist
  • ~没有更多了~
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文