Java比赛状况

发布于 2025-02-06 16:58:31 字数 805 浏览 3 评论 0原文

在这里的代码片段中,“母马不要吃燕麦”。没有打印。预计完成2000毫秒的睡眠后,它将运行该打印声明,但它永远不会到达那里。

public class BadThreads {
    
        static String message;
    
        private static class CorrectorThread
            extends Thread {
    
            public void run() {
                try {
                    sleep(1000); 
                } catch (InterruptedException e) {}
                // Key statement 1:
                message = "Mares do eat oats."; 
            }
        }
    
        public static void main(String args[])
            throws InterruptedException {
    
            (new CorrectorThread()).start();
            message = **"Mares do not eat oats.**";
            Thread.sleep(2000);
            // Key statement 2:
            System.out.println(message);
        }
    }

In the code snippet here under, "Mares do not eat oats." is not getting printed. It is expected that after completing sleep of 2000ms, it will run that print statement, but it is never reaching there.

public class BadThreads {
    
        static String message;
    
        private static class CorrectorThread
            extends Thread {
    
            public void run() {
                try {
                    sleep(1000); 
                } catch (InterruptedException e) {}
                // Key statement 1:
                message = "Mares do eat oats."; 
            }
        }
    
        public static void main(String args[])
            throws InterruptedException {
    
            (new CorrectorThread()).start();
            message = **"Mares do not eat oats.**";
            Thread.sleep(2000);
            // Key statement 2:
            System.out.println(message);
        }
    }

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

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

发布评论

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

评论(1

灯角 2025-02-13 16:58:31

您标记的陈述已得到联系。

当您的主线程入睡时,“校正”将消息的价值改变为“母马确实吃燕麦”。 并且不打印消息。然后校正完成执行。

主线程从睡眠中醒来,并打印出变量消息的价值,现在是“母马确实吃燕麦”。

请注意,变量消息均由两个线程共享。也许您习惯了C fork()语句,该语句将启动一个新的过程,随后将不再与主线程共享内存。

The statement you marked is being reached.

While your main-Thread sleeps, the "CorrectorThread" changes the value of message to "Mares do eat oats." and does not print the message. CorrectorThread then finished execution.

main-Thread wakes up from its sleep and prints the value of the variable message, which is now "Mares do eat oats."

Note that the variable message is shared by both threads. Maybe you are used to C's fork() statement, which would launch a new process, and would subsequently not share the memory with the main-Thread anymore.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文