声明主方法同步

And*_*san 4 java concurrency multithreading

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

这样的构造有什么实际功能?

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!");
    }
}
Run Code Online (Sandbox Code Playgroud)

Tud*_*dor 5

它可能用作临时的“应用程序关闭处理程序”,在应用程序完全完成之前执行一些清理任务。不过还是挺做作的...