程序入口:
public class User {
public static void main(String[] args) {
// TODO Auto-generated method stub
SendMessage msg = new SendMessage(new SendMessage.SendMsg() {
@Override
public void send(String msg) {
// TODO Auto-generated method stub
System.out.println(msg);
}
});
msg.run();
}
}
含有接口的类对象:
public class SendMessage {
private SendMsg sendMsg;
private int count = 0;
public SendMessage(SendMsg sendMsg) {
this.sendMsg = sendMsg;
}
public void run() {
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while(!Thread.interrupted()) {
try {
count++;
if(count == 5) {
count = 0;
sendMsg.send("马上要下课了,大家来搞王者"); //每隔5秒一个回调
}
Thread.sleep(1000);
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
}).start();
}
//定义接口
public interface SendMsg{
void send(String msg);//发送一条消息
}
}