本系列文章导航
本文主要解决的问题是:
如何使其Swing程序只能运行一个实例?
抛开Swing, 我们的程序是通过java 命令行启动一个进程来执行的,该问题也就是说要保证这个进程的唯一性,当然如果能够访问系统的接口,得到进程的信息来判断是否已有进程正在运行,不就解决 了吗?但是如何访问系统的接口呢?如何要保证在不同的平台上都是OK的呢?我的思路是用文件锁,当然我相信肯定有更好的方法,呵呵,希望读者能够指出。
文件锁是JDK1.4 NIO提出的,可以在读取一个文件时,获得文件锁,这个锁应该是系统维护的,JVM应该是调用的系统文件锁机制,例子如下:
packageconcurrentstudy;importjava.io.FileNotFoundException;importjava.io.IOException;importjava.io.RandomAccessFile;importjava.nio.channels.FileChannel;importjava.nio.channels.FileLock;/***@authorvma*/
public classtemp1 {public static void main(String args[]) throwsFileNotFoundException, InterruptedException, IOException {
RandomAccessFile r= new RandomAccessFile("d://testData.java", "rw");
FileChannel temp=r.getChannel();
FileLock fl=temp.lock();
System.out.println(fl.isValid());
Thread.sleep(100000);
temp.close();
}
}
当代码获得锁后:我们试图编辑这个文件是就会:
如果在启动一个Java Main方法时:
packageconcurrentstudy;importjava.io.FileNotFoundException;importjava.io.IOException;importjava.io.RandomAccessFile;importjava.nio.channels.FileChannel;importjava.nio.channels.FileLock;public classTemp2 {public static void main(String args[]) throwsFileNotFoundException, InterruptedException, IOException {
RandomAccessFile r= new RandomAccessFile("d://testData.java", "rw");
FileChannel temp=r.getChannel();
FileLock fl=temp.tryLock();
System.out.println(fl== null);
temp.close();
}
}
返回的结果是 ture , 也就是得不到文件的锁。
这就是对于进程唯一性问题我的解决思路,通过锁定文件使其再启动时得不到锁文件而无法启动。
说到这里,跟今天Swing中的EDT好像还没有关系,对于Swing程序,Main方法中一般像这样:
public static voidmain(String[] args) {try{
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
}catch(Exception e) {
}//Create the top-level container and add contents to it.
JFrame frame = new JFrame("SwingApplication");
SwingApplication app= newSwingApplication();
Component contents=app.createComponents();
frame.getContentPane().add(contents, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
启动Jfr