休眠

忘是亡心i 2023-06-04 07:56 71阅读 0赞

Java编程思想
并发
练习6:创建一个任务,它将睡眠1至10秒之间的随机数量的时间,然后显示它的睡眠时间并退出,创建并运行一定数量的这种任务。

  1. import java.util.concurrent.TimeUnit;
  2. public class Sleep implements Runnable{
  3. protected static int times = 0;
  4. public Sleep() {
  5. }
  6. public Sleep(int times) {
  7. this.times = times;
  8. }
  9. public void sleep(){
  10. try {
  11. System.out.print("我要睡一会儿觉");
  12. int sleepTime = (int)(Math.random()*10000);
  13. TimeUnit.MILLISECONDS.sleep(sleepTime);
  14. System.out.println(" 我睡了"+sleepTime/1000+"秒");
  15. }catch(InterruptedException e) {
  16. System.out.println("Interrupted");
  17. }
  18. }
  19. @Override
  20. public void run() {
  21. // TODO Auto-generated method stub
  22. for(int i=0;i<times;i++) {
  23. sleep();
  24. }
  25. System.out.println("我睡了"+times+"次");
  26. }
  27. }
  28. import java.util.concurrent.ExecutorService;
  29. import java.util.concurrent.Executors;
  30. public class TestSleep {
  31. public static void main(String[] args) {
  32. ExecutorService exec = Executors.newCachedThreadPool();
  33. exec.execute(new Sleep(3));
  34. exec.shutdown();
  35. }
  36. }

虽然写的不太恰当,嗯,就这样吧。

发表评论

表情:
评论列表 (有 0 条评论,71人围观)

还没有评论,来说两句吧...

相关阅读

    相关 休眠

    Java编程思想 并发 练习6:创建一个任务,它将睡眠1至10秒之间的随机数量的时间,然后显示它的睡眠时间并退出,创建并运行一定数量的这种任务。 import

    相关 线程的休眠

    线程对象一旦调用其`start`方法之后,就会运行,运行的就是`run`方法中的代码,等到`run`方法中的代码运行结束,线程就执行完成。