声明主方法同步 [英] Declaring the main method synchronized

查看:98
本文介绍了声明主方法同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到一个Java示例,其主要方法标记为synchronized,调用另一个静态同步方法。结果是,基本上,只有在main方法返回后,另一个方法才会在单独的线程上运行。

I saw a Java example that had a main method labeled as synchronized, calling another static synchronized method. The effect is that, basically, the other method runs on the separate thread only after the main method has returned.

这样的构造有哪些实际功能?

What practical functionality would such a construct have?

public class SynchronisedMain {

    public static synchronized void main(String[] args) throws InterruptedException {
        new Thread(new Runnable() {
            @Override
            public void run() {
                thingy();               
            }
        }).start();
        System.out.println("Kickstarted thingy thread.");
        TimeUnit.MILLISECONDS.sleep(1000);
    }

    public static synchronized void thingy() {
        System.out.println("Thingy!");
    }
}


推荐答案

这是可能有用作临时应用程序关闭处理程序,在应用程序完成之前执行一些清理任务。尽管如此......这是非常做作的。

It's probably useful as a makeshift "application closed handler", doing some cleanup duty before the app finishes entirely. It's pretty contrived though...

这篇关于声明主方法同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆