Demo04.java 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package J20250801.homework;
  2. import java.text.SimpleDateFormat;
  3. import java.util.Date;
  4. import java.util.Random;
  5. import java.util.concurrent.ScheduledFuture;
  6. import java.util.concurrent.ScheduledThreadPoolExecutor;
  7. import java.util.concurrent.TimeUnit;
  8. /**
  9. * @author WanJl
  10. * @version 1.0
  11. * @title Demo03
  12. * @description
  13. * @create 2025/8/1
  14. */
  15. public class Demo04 {
  16. private Random random=new Random();
  17. //时间日期格式化对象
  18. private static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  19. //开启监控的方法
  20. public void startMonitoring(){
  21. //创建2个核心线程数为2的定时线程池
  22. ScheduledThreadPoolExecutor pool=new ScheduledThreadPoolExecutor(2);
  23. //ScheduledFuture<?> scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnit unit)
  24. //command - 要执行的任务
  25. //initialDelay - 延迟第一次执行的时间
  26. //period - 连续执行之间的时期
  27. //unit - initialDelay和period参数的时间单位
  28. pool.scheduleAtFixedRate(()->{
  29. try {
  30. //监控系统状态
  31. monitoringSystemStatus();
  32. } catch (InterruptedException e) {
  33. //捕获中断异常
  34. System.out.println("监控任务被中断"+e.getMessage());
  35. Thread.currentThread().interrupt(); //添加一个中断标志,到底什么时候中断,由线程自己和CPU决定
  36. }
  37. },1,10,TimeUnit.SECONDS);
  38. //主线程运行2分钟后关闭定时线程池
  39. try {
  40. TimeUnit.MINUTES.sleep(2);
  41. } catch (InterruptedException e) {
  42. e.printStackTrace();
  43. }
  44. //关闭线程池,允许当前任务执行完毕
  45. pool.shutdown();
  46. try {
  47. //等待30秒,让剩余的任务完成
  48. if (!pool.awaitTermination(30,TimeUnit.SECONDS)){
  49. //30秒之后,强制关闭
  50. pool.shutdownNow();
  51. }
  52. System.out.println("系统已经停止");
  53. } catch (InterruptedException e) {
  54. e.printStackTrace();
  55. }
  56. }
  57. /**
  58. * 监控系统状态
  59. */
  60. public void monitoringSystemStatus() throws InterruptedException {
  61. //模拟监控系统时间5秒
  62. Thread.sleep(5000);
  63. //随机生产CPU和内存的使用率
  64. int cpu=5+random.nextInt(76);// 5~80%
  65. int memory=20+random.nextInt(71); //20~90%
  66. //获取当前的时间并且进行格式化
  67. String currentTime = sdf.format(new Date());
  68. //打印监控信息
  69. System.out.printf("监控时间:%s ,CPU:%d%% ,内存:%d%% \n",currentTime,cpu,memory);
  70. System.out.printf("监控时间:%s ,CPU:%d ,内存:%d \n",currentTime,cpu,memory);
  71. }
  72. public static void main(String[] args) {
  73. Demo04 demo04=new Demo04();
  74. demo04.startMonitoring();
  75. }
  76. }