Java如何实现延时访问

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

方法一

多线程阻塞实现方式

MyTask
package abc;

import java.util.concurrent.*;

public class MyTask implements Callable<Integer> {

    private int num;

    private int price;

    public MyTask(int num, int price) {
        this.num = num;
        this.price = price;
    }


    public int add(int m, int n) {
        System.out.println("执行运算..."+"\n");
        return m * n;
    }

    @Override
    public Integer call() throws Exception {
        //睡眠5秒
        Thread.sleep(5 * 1000L);
        return add(num,price);
    }
}
测试类
package abc;

import org.junit.Test;

import java.util.concurrent.FutureTask;

public class ThreadTest {

    @Test
    public void c() throws Exception {

        MyTask task = new MyTask(10,20);
        FutureTask<Integer> resultObject = new FutureTask<Integer>(task);
        new Thread(resultObject).start();
        //阻塞当前线程
        int result = resultObject.get();
        System.out.println(result);
    }
}

方法二

通过Timer定时器实现

TestTimerTask
package abc;

import java.util.Date;
import java.util.TimerTask;

public class TestTimerTask extends TimerTask {

    private String username;

    private int age;

    public TestTimerTask(String username, int age) {
        this.username = username;
        this.age = age;
    }

    @Override
    public void run() {
        // 处理业务逻辑
        System.out.println("开始处理.");
        System.out.println("大家好,我叫" + username + ",今年" + age + "岁");
        System.out.println("结束时间:"+new Date().toLocaleString());
        System.gc();
        cancel();
    }
}
测试类
package abc;


import java.util.Date;
import java.util.Timer;

public class TimerTest {

    public static void main(String[] args) {
        System.out.println("开始时间:"+new Date().toLocaleString());
        Timer timer = new Timer();
        System.out.println("一:"+timer);
        timer.schedule(new TestTimerTask("张三",20),5000);
        System.out.println(timer);
    }
}
输出结果
开始时间:2018-11-8 17:21:49
一:java.util.Timer@6acbcfc0
java.util.Timer@6acbcfc0
开始处理.
大家好,我叫张三,今年20岁
结束时间:2018-11-8 17:21:54

Process finished with exit code 0
注意
  • Timer测试不能用单元测试
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值