Java如何实现延时访问

调用某个方法后,我们需要程序过一段时间再去处理,就可以用多线程阻塞Timer定时器来实现

方法一

多线程阻塞实现方式

MyTask

  1. package abc;
  2. import java.util.concurrent.*;
  3. public class MyTask implements Callable<Integer> {
  4. private int num;
  5. private int price;
  6. public MyTask(int num, int price) {
  7. this.num = num;
  8. this.price = price;
  9. }
  10. public int add(int m, int n) {
  11. System.out.println("执行运算..."+"\n");
  12. return m * n;
  13. }
  14. @Override
  15. public Integer call() throws Exception {
  16. //睡眠5秒
  17. Thread.sleep(5 * 1000L);
  18. return add(num,price);
  19. }
  20. }

测试类

  1. package abc;
  2. import org.junit.Test;
  3. import java.util.concurrent.FutureTask;
  4. public class ThreadTest {
  5. @Test
  6. public void c() throws Exception {
  7. MyTask task = new MyTask(10,20);
  8. FutureTask<Integer> resultObject = new FutureTask<Integer>(task);
  9. new Thread(resultObject).start();
  10. //阻塞当前线程
  11. int result = resultObject.get();
  12. System.out.println(result);
  13. }
  14. }

方法二

通过Timer定时器实现

TestTimerTask

  1. package abc;
  2. import java.util.Date;
  3. import java.util.TimerTask;
  4. public class TestTimerTask extends TimerTask {
  5. private String username;
  6. private int age;
  7. public TestTimerTask(String username, int age) {
  8. this.username = username;
  9. this.age = age;
  10. }
  11. @Override
  12. public void run() {
  13. // 处理业务逻辑
  14. System.out.println("开始处理.");
  15. System.out.println("大家好,我叫" + username + ",今年" + age + "岁");
  16. System.out.println("结束时间:"+new Date().toLocaleString());
  17. System.gc();
  18. cancel();
  19. }
  20. }

测试类

  1. package abc;
  2. import java.util.Date;
  3. import java.util.Timer;
  4. public class TimerTest {
  5. public static void main(String[] args) {
  6. System.out.println("开始时间:"+new Date().toLocaleString());
  7. Timer timer = new Timer();
  8. System.out.println("一:"+timer);
  9. timer.schedule(new TestTimerTask("张三",20),5000);
  10. System.out.println(timer);
  11. }
  12. }

输出结果

  1. 开始时间:2018-11-8 17:21:49
  2. 一:java.util.Timer@6acbcfc0
  3. java.util.Timer@6acbcfc0
  4. 开始处理.
  5. 大家好,我叫张三,今年20
  6. 结束时间:2018-11-8 17:21:54
  7. Process finished with exit code 0

注意

  • Timer测试不能用单元测试

0
2
0

添加评论

正在回复:
取消
1
0
2
0