zoukankan      html  css  js  c++  java
  • scheduleAtFixedRate 和 timer 执行对比

    自由自在

    main

    package com.adao.simulater.socket;
    /**
     * 客户端测试类
     * 
     * @author adao 2020-06-22
     */
    public class socketClientTest {
    public static Socket client;
        
        private static ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(10);
    
        public static void main(String[] args) throws IOException {
    
            client = ClientManager.getConnect();
            long terminalId = Long.parseLong("1000000000001");long delay = 1000 * 5; // 时延
                long period = 1000 * 1; // 频率
            for (int j = 0; j < 1000; j++) {
            if (client.isConnected()) {
                keepAlive(client, terminalId, period);
    //            heartbeatTask(client, terminalId, delay, period);
    
            }
            terminalId++;
            }
        }
    
        public static void keepAlive(Socket client, Long terminalId, long period) {
            Thread keepAliveThread = new Thread(new KeepAliveThread(client, terminalId, period));
            // 延迟10秒执行心跳线程
            threadPool.scheduleAtFixedRate(keepAliveThread, 10000, period, TimeUnit.MILLISECONDS);
        }
        
        public static void heartbeatTask(Socket client, Long terminalId, long delay, long period) {
            Timer timer = new Timer();
            timer.schedule(new HeartbeatTask(client, terminalId), delay, period);
        }
    
    }

    KeepAliveThread

    package com.adao.simulater.socket;
    
    import java.io.IOException;
    import java.io.OutputStream;
    import java.net.Socket;
    
    import org.apache.log4j.Logger;
    
    /**
     * 客户端心跳
     * 
     * @author Adao 2020-06-29
     */
    public class KeepAliveThread implements Runnable {
        private final static Logger logger = Logger.getLogger(KeepAliveThread.class);
    
        private KeepAliveThread() {
        }
    
        public KeepAliveThread(Socket cleint, long terminalId, long period) {
            this.client = cleint;
            this.terminalId = terminalId;
        }
    
        Socket client;
        long terminalId;
    
        public void run() {
            try {
                if (client.isConnected()) {
                    OutputStream os = client.getOutputStream();
                    logger.info("终端ID : " + terminalId + ", 发送心跳报文." + " name:" + Thread.currentThread().getName());
                    os.write("send heart beat data package !".getBytes());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
    }

    HeartbeatTask

    package com.linyang.simulater.task;
    
    import java.io.IOException;
    import java.io.OutputStream;
    import java.net.Socket;
    import java.util.TimerTask;
    
    import org.apache.log4j.Logger;
    
    public class HeartbeatTask extends TimerTask {
        private final static Logger logger = Logger.getLogger(HeartbeatTask.class);
        public Socket client;
        public long terminalId;
    
        public HeartbeatTask(Socket cleint, long terminalId) {
            this.client = cleint;
            this.terminalId = terminalId;
        }
    
        OutputStream os = null;
    
        @Override
        public void run() {
            try {
                if (client.isConnected()) {
                    os = client.getOutputStream();
                    logger.info("终端ID : " + terminalId + ", 发送心跳报文." + " name:" + Thread.currentThread().getName());
                    os.write("send heart beat data package !".getBytes());
                    os.flush();
                } else {
                    logger.info("终端ID : " + terminalId + ", socket未连接.");
                }
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("获取连接失败." + e);
            }
    
        }
    
    }

    ClientManager

    package com.adao.simulater.socket;
    
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.net.Socket;
    import java.util.Properties;
    
    import org.apache.log4j.Logger;
    
    import com.linyang.simulater.common.PropertiesUtil;
    import com.linyang.simulater.util.StrUtil;
    
    /**
     * 
     * 负责客户端管理
     *
     */
    public class ClientManager {
        private final static Logger logger = Logger.getLogger(ClientManager.class);
    
        public static Socket client;
    
        public static Socket getClient() {
            return client;
        }
    
    
        /**
         * 创建socket连接
         */
        public static Socket getConnect() {
    
            ClientManager.checkPort(serverPort);
            serverAddress = ClientManager.checkIp(serverAddress);
    
            try {
                client = new Socket();
                client.connect(new InetSocketAddress("127.0.0.1", 3000), 3000);
                logger.info("Socket客户端连接成功 : " + client);
            } catch (IOException e) {
                logger.error("Socket客户端连接失败!", e);
            }
    
            return client;
    
        }
    
        public static void disconnect() {
            // 关闭所有服务
            if (client != null && client.isConnected()) {
                try {
                    client.shutdownOutput();
                    client.shutdownInput();
                    client.getOutputStream().close();
                    client.getInputStream().close();
                    client.close();
                } catch (IOException e) {
                    logger.error(e);
                }
            }
    
        }
    
        public static void checkPort(int port) {
            if (port < 1 || port > 65534) {
                logger.error("端口配置错误,超出范围[1,65534], 程序终止启动。");
                System.exit(0);
            }
        }
    
        public static String checkIp(String ipAddr) {
            if (null == ipAddr || "".equals(ipAddr.trim())) {
                ipAddr = "127.0.0.1";
            } else {
                if (!StrUtil.isIp(ipAddr)) {
                    logger.error("服务端IP设置错误,程序终止启动");
                    System.exit(0);
                }
            }
            return ipAddr;
        }
    
    }

    执行结果:

    线程

    timer

     从执行结果可以看出 线程消耗cpu更高,不知道有大神给解释一下没,在其他帖子看到推荐用线程比任务要快

    不完美

  • 相关阅读:
    为什么我会被淘汰?
    2017-3-27日碎碎念
    (原创)我对未来的人类的发展,以及AI技术发展的一些思考。
    八大排序算法图文讲解
    PE病毒初探——向exe注入代码
    [转]Patch文件结构详解
    芝麻信用商家接入指南
    如何成为一名好的程序员的一些个人经验
    .NET CoreCLR开发人员指南(上)
    七牛云:ckeditor JS SDK 结合 C#实现多图片上传。
  • 原文地址:https://www.cnblogs.com/adao21/p/13226393.html
Copyright © 2011-2022 走看看