java 事件分发线程_深入浅出Java多线程(2)-Swing中的EDT(事件分发线程) [转载]...

本系列文章导航

本文主要解决的问题是:

如何使其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();

}

}

当代码获得锁后:我们试图编辑这个文件是就会:

1.JPG

如果在启动一个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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值