package J20250801.homework; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * @author WanJl * @version 1.0 * @title Demo03 * @description * @create 2025/8/1 */ public class Demo04 { private Random random=new Random(); //时间日期格式化对象 private static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //开启监控的方法 public void startMonitoring(){ //创建2个核心线程数为2的定时线程池 ScheduledThreadPoolExecutor pool=new ScheduledThreadPoolExecutor(2); //ScheduledFuture scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnit unit) //command - 要执行的任务 //initialDelay - 延迟第一次执行的时间 //period - 连续执行之间的时期 //unit - initialDelay和period参数的时间单位 pool.scheduleAtFixedRate(()->{ try { //监控系统状态 monitoringSystemStatus(); } catch (InterruptedException e) { //捕获中断异常 System.out.println("监控任务被中断"+e.getMessage()); Thread.currentThread().interrupt(); //添加一个中断标志,到底什么时候中断,由线程自己和CPU决定 } },1,10,TimeUnit.SECONDS); //主线程运行2分钟后关闭定时线程池 try { TimeUnit.MINUTES.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } //关闭线程池,允许当前任务执行完毕 pool.shutdown(); try { //等待30秒,让剩余的任务完成 if (!pool.awaitTermination(30,TimeUnit.SECONDS)){ //30秒之后,强制关闭 pool.shutdownNow(); } System.out.println("系统已经停止"); } catch (InterruptedException e) { e.printStackTrace(); } } /** * 监控系统状态 */ public void monitoringSystemStatus() throws InterruptedException { //模拟监控系统时间5秒 Thread.sleep(5000); //随机生产CPU和内存的使用率 int cpu=5+random.nextInt(76);// 5~80% int memory=20+random.nextInt(71); //20~90% //获取当前的时间并且进行格式化 String currentTime = sdf.format(new Date()); //打印监控信息 System.out.printf("监控时间:%s ,CPU:%d%% ,内存:%d%% \n",currentTime,cpu,memory); System.out.printf("监控时间:%s ,CPU:%d ,内存:%d \n",currentTime,cpu,memory); } public static void main(String[] args) { Demo04 demo04=new Demo04(); demo04.startMonitoring(); } }