1. 程式人生 > >java事件,每隔5秒向返回當前時間

java事件,每隔5秒向返回當前時間

建立工具類,每隔5秒返回當前時間

 

package FiveTime;

import java.util.ArrayList;
import java.util.List;

import jinghai.base.notifier.Notifier;
import jinghai.base.time.LocalDateTime;

public class FivesTimer extends Thread{

    public List<Notifier<LocalDateTime>> timelist = new ArrayList<Notifier<LocalDateTime>>();
    
    
public void run() { try { doRun(); } catch (Exception e) { e.printStackTrace(); } } public void doRun() throws Exception { while(true) { doSleep(); for(Notifier<LocalDateTime> n:timelist) { n.notify(LocalDateTime.now()); } } }
public void doSleep() { try { sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } }

Receiver例項化工具類,每隔五秒輸出當前時間

package Receiver;

import FiveTime.FivesTimer;
import jinghai.base.notifier.Notifier;
import jinghai.base.time.LocalDateTime;

public class Receiver { public FivesTimer fivesTimer; public Receiver() { fivesTimer = new FivesTimer(); fivesTimer.timelist.add(new Notifier<LocalDateTime>() { @Override public void notify(LocalDateTime time) { show(time); } }); } public void show(LocalDateTime time) { System.out.println(time); } public void run() { fivesTimer.start(); } }

main函式

package Receiver;

public class Test {

    public static void main(String[] args) {
        Receiver receiver = new Receiver();
        receiver.run();
    }
}