黑名单实战

package com.laoyang.Thread.JUC包下的并发容器;

import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author:Kevin
 * @create: 2023-10-19 19:35
 * @Description: 黑名单实战
 */

public class IpDemo {

    private static final CopyOnWriteArrayList list = new CopyOnWriteArrayList<>();

    //添加默认黑名单
    static {
        list.add("Ip0");
        list.add("Ip1");
        list.add("Ip2");

    }

    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                //模拟接入
                try {
                    Thread.sleep(new Random().nextInt(5000));
                }catch (Exception e){}
                String currentIP = "Ip" + new Random().nextInt(3);

                if (list.contains(currentIP)){
                    System.out.println(Thread.currentThread().getName() + " IP " +
                            currentIP + "命中黑名单,拒绝接入处理");
                    return;
                }
                System.out.println(Thread.currentThread().getName() + " IP " +
                        currentIP + "接入处理...");
            }
        };

        new Thread(runnable, "thread1").start();
        new Thread(runnable, "thread2").start();
        new Thread(runnable, "thread3").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(new Random().nextInt(2000));
                }catch (Exception e){}

                String ip = "Ip3";
                list.add(ip);
                System.out.println(Thread.currentThread().getName() + " 添加了新的非法" +
                        ip+ " + newBlackIP");
            }
        }).start();
    }
}

你可能感兴趣的:(windows)