利用文件锁,实现单一线程运行

前端之家收集整理的这篇文章主要介绍了利用文件锁,实现单一线程运行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

public class MainApp {
boolean packFrame = false;

/**
* Construct and show the application.
*/
public MainApp() {
// 控制程序只能开启一次
// SingleThread single = new SingleThread();
// single.start();
if (instanceControl()) {
System.out.println("集中出单影像提取服务已经在运行中,本服务不能启动,自动退出。");
System.exit(0);
}

MainFrame frame = new MainFrame();
// Validate frames that have preset sizes
// Pack frames that have useful preferred size info,e.g. from their
// layout
if (packFrame) {
frame.pack();
} else {
frame.validate();
}

// Center the window
frame.setLocation(GUIUtil.getLocationForWindow(new Point(),Toolkit
.getDefaultToolkit().getScreenSize(),frame.getSize()));
frame.setVisible(true);

// 服务自动启动,不需要手动点开启服务按钮或菜单
frame.startServerAuto();
}

/**
* Application entry point.
*
* @param args
* String[]
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
// 设计不同的显示风格
UIManager.LookAndFeelInfo[] lookAndFeelInfo = UIManager
.getInstalledLookAndFeels();
UIManager.setLookAndFeel(lookAndFeelInfo[0].getClassName());
} catch (Exception exception) {
exception.printStackTrace();
}
// log4j.properties配置文件和jzcd.jar包放在同一目录下
PropertyConfigurator.configure(System.getProperty("user.dir")
+ "/log4j.properties");
new MainApp();
}
});
}

public static boolean instanceControl() { boolean flag = false; try { RandomAccessFile raf = new RandomAccessFile(new File( "jzcdService.lck"),"rw"); FileChannel fc = raf.getChannel(); FileLock lock = fc.tryLock(); if (lock == null) { flag = true; } } catch (Exception ex) { ex.printStackTrace(); } return flag; } }

原文链接:https://www.f2er.com/javaschema/286888.html

猜你在找的设计模式相关文章