Java桌面程序实现“单例”

来源:互联网 发布:直播盒子源码 编辑:程序博客网 时间:2024/06/07 02:57

单例控制类:

import java.net.ServerSocket;import java.net.Socket;/** * @author WangW *  */public class InstanceControl implements Runnable {/** * 原理:先申请连接,如果不成功,则创建一个服务端,程序就创建了一个示例。 *   下次再运行的时候,又连接,如果连接上了,则证明已经创建了此端口的一个服务, *   证明有实例存在,就退出。 */public void run() {try {new Socket("127.0.0.1", 12345);// 创建socket,连接12345端口System.exit(0); // 连接成功,说明有实例存在,则退出} catch (Exception e) {}try {ServerSocket server = new ServerSocket(12345);// 创建socket,连接22222端口while (true) {server.accept(); // 接受连接请求}} catch (Exception e) {e.printStackTrace();}}}


测试类:

import javax.swing.JFrame;/** * @author WangW * */public class MainSingle {public MainSingle() {JFrame frame = new JFrame("Single");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setSize(200, 100);frame.setVisible(true);}public static void main(String[] args) { InstanceControl   ic   =   new   InstanceControl(); Thread t = new Thread(ic);  t.start(); new MainSingle();}}


 

这只是使用端口的方法,还有其他的待研究····