设计一个延迟N分钟执行的实现

比如,延迟5分钟。

1、写数据

一个圆环上有5个存储节点,

第一个节点存当前时间的分钟对5取余为0的数据;

第二个节点存当前时间的分钟对5取余为1的数据;

以此类推;

2、读取数据的程序,

计算当前时间的分钟对5取余,记为A;然后A+1再对5取余,记为B;

(优化下,获取当前时间的分钟+1,然后对5取余,记为B)

B记为当前需要读取的节点数据;

3、代码如下:

import java.text.SimpleDateFormat;
import java.util.Date;

public class TestCircle {

    public static final SimpleDateFormat min = new SimpleDateFormat("mm");
    public static final SimpleDateFormat time = new SimpleDateFormat("HH:mm:ss");
    
    public static void main(String[] args) {
        
        // 第一个线程:生产数据
        new Thread(new Runnable(){
            @Override
            public void run() {
                System.out.println("produce...");
                while(true) {
                    TestCircle.produce();
                }
            }
        }).start();
        
        // 第二个线程:消费数据
        new Thread(new Runnable(){
            @Override
            public void run() {
                System.out.println("consume...");
                while(true) {
                    TestCircle.consume();
                }
            }
        }).start();
    }
    
    /**
     * 随机生成数据
     */
    public static void produce() {
        // 随机等待时间
        long millis = ((Double)(Math.random() * 1000 * 100)).longValue();
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        // 生产数据存放位置
        Date date = new Date(); // 当前时间
        String mm = min.format(date); // 获取分钟
        int key = Integer.parseInt(mm) % 5; // 当前分钟对5取余数
        System.out.println(TestCircle.time.format(date) + "加入" + key);
    }
    
    public static void consume() {
        try {
            Thread.sleep(1000 * 35);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Date date = new Date();
        String mm = min.format(date); // 获取分钟
        int key = Integer.parseInt(mm) % 5; // 取余数
        int tar =  (key+1) % 5;
        System.out.println(TestCircle.time.format(date) + "消费" + tar);
    }
    
}

 

posted @ 2017-12-13 18:41  wbinbin  阅读(358)  评论(0)    收藏  举报