timer 的使用

Cancel来把task 停止, schedule来启动


import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.LinkedBlockingQueue;

public class TimerClient {

static LinkedBlockingQueue words = new LinkedBlockingQueue();
static{
System.setProperty("file.encoding","UTF-8");
words.add("请妹子喝奶茶 ");
words.add("她问这杯夺钱一杯啊 ");
words.add("我说12块 ");
words.add("她摇手说不喝了 口红很贵 ");
words.add("。。。。。。");

}

public static void main(String[] args) {
Timer t = new Timer();
NewTimerTask cr = new NewTimerTask(t);

Calendar cad = Calendar.getInstance();
cad.add(Calendar.SECOND, 1);

t.schedule(cr, cad.getTime(), 1500);

while(words.size() == 0){
cr.cancel();
t.cancel();
System.exit(0);
}
}

public static class NewTimerTask extends TimerTask {
Timer tm;

public NewTimerTask(Timer tt) {
tm = tt;
}

@Override
public void run() {
System.out.println(words.poll() );
if(words.size() == 0) {
try {
tm.cancel();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
}

}

你可能感兴趣的:(timer)