戳下方卡片,回复暗号【Java面试题】即可获取大厂面试题

package com.qfedu.day85.task;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
public class PrintTask {
// 任务默认同步执行的
@Async // 表示异步执行的注解
@Scheduled(cron = "5 * * * * ?")// 每分钟的第5秒触发定时任务
public void printInfo() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
System.out.println(sdf.format(new Date()) + ": print info test");
}
}





package com.qfedu.day85.task;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
@Component
public class PrintTask {
// 注入RedissonClient 对象
@Resource
private RedissonClient redissonClient;
@Async
@Scheduled(cron = "0/5 * * * * ?")
public void printInfo2() {
// 获取锁对象,参数表示redis中key值
RLock taskLock = redissonClient.getLock("taskLock");
try {
// 尝试加锁,
// 第一个参数,表示加锁的重试时间,如果锁被占用,在指定时间内尝试加锁
// 第二个参数,表示锁过期时间
// 返回true/false
// 本例中,第一个参数是0,表示如果没有加上锁,直接返回false
if (taskLock.tryLock(0, 10, TimeUnit.SECONDS)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
System.out.println(sdf.format(new Date()) + ": print info test");
// Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (taskLock.isLocked()) {
// 判断是否当前线程拥有该锁
if (taskLock.isHeldByCurrentThread()) {
// 释放锁
taskLock.unlock();
}
}
}
}
}





原文作者:Java架构栈;如有侵权,请联系管理员删除。