zoukankan      html  css  js  c++  java
  • java,有用的代码片段

    在我们写程序的过程中,往往会经常遇到一些常见的功能。而这些功能或效果往往也是相似的,解决方案也相似。下面是我在写代码的过程中总结的一些有用的代码片段。

    1、在多线程环境中操作同一个Collection,会出现线程同步的问题,甚至有时候会抛出异常

    解决方案:使用Collections.synchronizeMap(),并使用如下代码访问或者删除元素

     1 public class ConcurrentMap {
     2     private Map<String, String> map = Collections.synchronizedMap(new HashMap<>());
     3 
     4     public synchronized void add(String key, String value) {
     5         map.put(key, value);
     6     }
     7 
     8     public synchronized void remove(String key) {
     9         Set<Map.Entry<String, String>> entries = map.entrySet();
    10         Iterator<Map.Entry<String, String>> it = entries.iterator();
    11         while (it.hasNext()) {
    12             Map.Entry<String, String> entry = it.next();
    13             if (key.equals(entry.getKey())) {
    14                 it.remove();
    15             }
    16         }
    17     }
    18 
    19     public synchronized void remove2(String key) {
    20         Set<Map.Entry<String, String>> entries = map.entrySet();
    21         entries.removeIf(entry -> key.equals(entry.getKey()));
    22     }
    23 }
    View Code

    2、根据URL获取ip

    解决方案,使用java.net.InetAddress工具类

    /**
         * 根据url获取对应的ip
         * @throws UnknownHostException UnknownHostException
         */
        @Test
        public void testGetIP() throws UnknownHostException {
            Pattern domainPattern = Pattern.compile("(?<=://)[a-zA-Z\.0-9]+(?=\/)");    //匹配域名
            String url = "http://ngcdn001.cnr.cn/live/zgzs/index.m3u8";
            Matcher matcher = domainPattern.matcher(url);
            if (matcher.find()) {
                InetAddress inetAddress = Inet4Address.getByName(matcher.group());
                String hostAddress = inetAddress.getHostAddress();
                System.out.println("hostAddress = " + hostAddress);
            }
        }
    View Code

     3、正确匹配URL的正则表达式

    解决方案:(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]  IP地址、前后有汉字、带参数的,都是OK的。

    辅助:RegexBuddy 正则神器

  • 相关阅读:
    MATLAB使用fft求取给定音频信号的频率
    python实现抓取必应图片设置桌面
    [原创]Nexus5 移植OneStep
    [原创]Nexus5 内核编译烧录过程记录
    repo版本切换
    pthread
    《Android进阶》Sqlite的使用
    【转】iOS夯实:ARC时代的内存管理
    【转】如何使App从后台返回前台时,显示指定界面
    【转】自定义UITableViewCell(registerNib: 与 registerClass: 的区别)
  • 原文地址:https://www.cnblogs.com/adeng/p/7521162.html
Copyright © 2011-2022 走看看