zoukankan      html  css  js  c++  java
  • 【翻译四】java-并发之线程暂停

    Pausing Execution with Sleep

    Thread.sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system. The sleep method can also be used for pacing, as shown in the example that follows, and waiting for another thread with duties that are understood to have time requirements, as with the SimpleThreads example in a later section.

    Two overloaded versions of sleep are provided: one that specifies the sleep time to the millisecond and one that specifies the sleep time to the nanosecond. However, these sleep times are not guaranteed to be precise, because they are limited by the facilities provided by the underlying OS. Also, the sleep period can be terminated by interrupts, as we'll see in a later section. In any case, you cannot assume that invoking sleep will suspend the thread for precisely the time period specified.

    The SleepMessages example uses sleep to print messages at four-second intervals:

     1 public class SleepMessages {
     2     public static void main(String args[])
     3         throws InterruptedException {
     4         String importantInfo[] = {
     5             "Mares eat oats",
     6             "Does eat oats",
     7             "Little lambs eat ivy",
     8             "A kid will eat ivy too"
     9         };
    10 
    11         for (int i = 0;
    12              i < importantInfo.length;
    13              i++) {
    14             //Pause for 4 seconds
    15             Thread.sleep(4000);
    16             //Print a message
    17             System.out.println(importantInfo[i]);
    18         }
    19     }
    20 }
    Notice that main declares that it throws InterruptedException. This is an exception that sleep throws when another thread interrupts the current thread while sleep is active. Since this application has not defined another thread to cause the interrupt, it doesn't bother to catch InterruptedException.
    简历: 三年国内著名软件公司Java信息系统开发经验。熟悉税务相关业务知识。一年以上互联网公司工作经验。 目标职位: Java研发工程师、大数据、推荐算法等。 目标城市: 北京,杭州,沈阳。 联系方式: 邮箱:hecuking@126.com
  • 相关阅读:
    samba服务器之无认证进入共享目录
    中断
    html里<div> <br /> <p>三者区别
    块级元素和内联元素
    div和span标签
    django添加装饰器
    cookie和session
    Django报错:__init__() missing 1 required positional argument: 'on_delete'
    pycharm创建新django app
    djiango控制语句
  • 原文地址:https://www.cnblogs.com/accipiter/p/3159754.html
Copyright © 2011-2022 走看看