声明主方法同步

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

这种结构有哪些实用function?

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!"); } } 

它可能是一个临时的“应用程序关闭处理程序”,在应用程序完成之前执行一些清理任务。 尽管如此……

没有任何东西说主要function只能用作程序的入口点。 作为静态,没有理由其他类不能调用SynchronisizedMain.main() 。 同步可防止多个实例同时执行,这可能是合乎需要的。