如何确保只能执行我的程序的一个实例? [英] How do I make sure only one instance of my program can be executed?

查看:119
本文介绍了如何确保只能执行我的程序的一个实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的程序,Java可执行文件.jar只运行一次。我制作了一个程序,但现在我希望用户不能打开多个实例....感谢您的时间......

I want my program, a Java executable .jar, to be run just once. I made a program but now I want users not to be able to open more than one instance ....thanks for your time...

我已经检查了服务器/客户端解决方案和锁定文件,但我不太了解它们,我也试图让它们在NetBeans中运行,没有运气......

I've checked the server/client solution and the lock file, but I don't understand them much, I also tried to make them run in NetBeans, with no luck...

推荐答案

您可以使用套接字 - ServerSocket只能侦听尚未使用的端口。第一次启动在端口上成功创建了一个ServerSocket实例 - 当该程序正在运行时,不能在该端口上成功创建其他ServerSocket。

You could use sockets - a ServerSocket can only listen on a port that's not already in use. The first launch successfully creates a ServerSocket instance on the port - while that program is running, no other ServerSocket can successfully be created on that port.

import java.io.IOException;
import java.net.ServerSocket;

public class OneInstance {

    private static ServerSocket SERVER_SOCKET;

    public static void main(String[] args) {
        try {
            SERVER_SOCKET = new ServerSocket(1334);
            System.out.println("OK to continue running.");
            System.out.println("Press any key to exit.");
            System.in.read();
        } catch (IOException x) {
            System.out.println("Another instance already running... exit.");
        }
    }
} 

这篇关于如何确保只能执行我的程序的一个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆