java 应用程序实例_保持java应用程序的单例实例

对于应用程序的单个实例,java中没有常规方法.

但是,您可以使用Socket编程技术来实现您的目标.

实例创建时,它会尝试侦听ServerSocket.如果它可以打开ServerSocket,则意味着没有该应用程序的另一个实例.因此,它会使ServerSocket保持活动状态,直到程序关闭.如果无法打开ServerSocket,则表示应用程序已经有另一个实例.因此,您可以静默退出应用程序.此外,关闭应用程序时无需重置设置.

试试下面的例子

public class SingletonApplication extends JFrame implements Runnable {

//count of tried instances

private int triedInstances = 0;

//the port number using

private static final int PORT = 5555;

public static void main(String[] args) {

SingletonApplication application = new SingletonApplication();

application.setTitle("My Singleton Application");

application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

application.setSize(500, 500);

application.setVisible(true);

}

public SingletonApplication() {

super();

//run socket listening inside a thread

Thread thread = new Thread(this);

thread.start();

}

@Override

public void run() {

try {

//create server socket

ServerSocket serverSocket = new ServerSocket(PORT);

//listing the socket to check new instances

while (true) {

try {

//another instance accessed the socket

serverSocket.accept();

//bring this to front

toFront();

//change the title (addtional);

triedInstances++;

setTitle("Tried another instances : " + triedInstances);

} catch (IOException ex) {

//cannot accept socket

}

}

} catch (IOException ex) {

//fail if there is an instance already exists

try {

//connect to the main instance server socket

new Socket(InetAddress.getLocalHost(), PORT);

} catch (IOException ex1) {

//do nothing

} finally {

//exit the system leavng the first instance

System.exit(0);

}

}

}

}

编辑:

另外:它可以通过客户端Socket将运行时参数传递给应用程序的主实例.因此,在调用accept()方法时,可以通过添加一些额外的代码来读取接受的Socket的InputStream,从而使主实例能够执行所需的任务,例如打开文件或播放音乐.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值