一道java编程题求大神指点

2024-11-07 06:46:01
推荐回答(2个)
回答1:

import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

public class AccessTask implements Count {

    AtomicLong count = new AtomicLong(0);
    CopyOnWriteArrayList list = new CopyOnWriteArrayList<>();
    //hr接口多线程访问
    @Override
    public void hr() {
        count.getAndAdd(1);
        System.out.println(Thread.currentThread().getName() +" 访问次数:"+count);
        list.add(System.currentTimeMillis());
    }

    @Override
    public DateState state() {
        DateState dateState = new DateState();

        int num = 0;
        long now = System.currentTimeMillis();

        long s1 = TimeUnit.SECONDS.toMillis(10);
        long s2 = TimeUnit.SECONDS.toMillis(60);
        long m1 = TimeUnit.MINUTES.toMillis(10);
        long m2 = TimeUnit.MINUTES.toMillis(60);

        if (list.size()>0) {
            for (int i = list.size()-1; i >-1 ; i--) {
                long time = now - list.get(i);
                num++;
                if (time                    dateState.setLast10Second(num);
                }
                if (time < s2) {
                    dateState.setLast60Second(num);
                }
                if (time                    dateState.setLast10Minute(num);
                }
                if (time < m2) {
                    dateState.setLast60Minute(num);
                } else {
                    break;
                }
            }
        }
        System.out.println(dateState);
        return dateState;
    }

}








import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class TestCount {
    public static void main(String[] args) {

        AccessTask accessTask = new AccessTask();
        ExecutorService pool = Executors.newFixedThreadPool(20);

        for (int i = 0; i < 100; i++) {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            pool.execute(new Runnable() {
                @Override
                public void run() {
                    accessTask.hr();
                    accessTask.state();

                }
            });
        }
            pool.shutdown();
    }
}

回答2:

我可以帮你写,私聊我发给你吧