Thread sleep примеры java

Метод thread sleep в Java – задержка по времени

Метод Thread.sleep() можно использовать для приостановки выполнения текущего потока на указанное время в миллисекундах. Значение аргумента в миллисекундах не может быть отрицательным, иначе оно выдает исключение IllegalArgumentException.

Существует еще один метод sleep(long millis, int nanos), который можно использовать для приостановки выполнения текущего потока на указанные миллисекунды и наносекунды. Допустимое значение nano second составляет от 0 до 999999.

InterruptedException возникает, если какой-либо поток прервал текущий поток. Прерванное состояние текущего потока очищается при возникновении этого исключения.

public static void sleep(long millis) throws InterruptedException

Как работает Thread Sleep?

Thread.sleep() взаимодействует с планировщиком потока, чтобы перевести текущий поток в состояние ожидания в течение указанного периода времени. По истечении времени, ожидания состояние потока изменяется на работоспособное состояние и ожидает ЦП для дальнейшего выполнения.

Таким образом, фактическое время ожидания текущего потока зависит от планировщика потока, который является частью операционной системы.

Пример thread sleep на Java

Вот простая программа на Java, в которой Thread.sleep() используется для задержки по времени основного потока на 2 секунды.

package com.journaldev.threads; public class ThreadSleep < public static void main(String[] args) throws InterruptedException < long start = System.currentTimeMillis(); Thread.sleep(2000); System.out.println("Sleep time in ms EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="eclipse">package com.tutorial; import java.lang.*; public class ThreadDemo implements Runnable < Thread t; public void run() < for (int i = 10; i < 13; i++) < System.out.println(Thread.currentThread().getName() + " " + i); try < // в течение 1000 миллисекунд Thread.sleep(1000); >catch (Exception e) < System.out.println(e); >> > public static void main(String[] args) throws Exception < Thread t = new Thread(new ThreadDemo()); // this will call run() function t.start(); Thread t2 = new Thread(new ThreadDemo()); // this will call run() function t2.start(); >>

Давайте скомпилируем и запустим программу, это даст следующий результат:
Thread-0 10
Thread-1 10
Thread-0 11
Thread-1 11
Thread-0 12
Thread-1 12

Читайте также:  direction

Средняя оценка 4.1 / 5. Количество голосов: 10

Спасибо, помогите другим — напишите комментарий, добавьте информации к статье.

Видим, что вы не нашли ответ на свой вопрос.

Напишите комментарий, что можно добавить к статье, какой информации не хватает.

Источник

Thread.sleep() in Java — Java Thread sleep

Thread.sleep() in Java - Java Thread sleep

The Java Thread.sleep() method can be used to pause the execution of the current thread for a specified time in milliseconds. The argument value for milliseconds cannot be negative. Otherwise, it throws IllegalArgumentException .

sleep(long millis, int nanos) is another method that can be used to pause the execution of the current thread for a specified number of milliseconds and nanoseconds. The allowed nanosecond values are between 0 and 999999 .

In this article, you will learn about Java’s Thread.sleep() .

How Thread.sleep Works

Thread.sleep() interacts with the thread scheduler to put the current thread in a wait state for a specified period of time. Once the wait time is over, the thread state is changed to a runnable state and waits for the CPU for further execution. The actual time that the current thread sleeps depends on the thread scheduler that is part of the operating system.

Java Thread.sleep important points

  1. It always pauses the current thread execution.
  2. The actual time the thread sleeps before waking up and starting execution depends on system timers and schedulers. For a quiet system, the actual time for sleep is near to the specified sleep time, but for a busy system, it will be a little bit longer.
  3. Thread.sleep() doesn’t lose any monitors or lock the current thread it has acquired.
  4. Any other thread can interrupt the current thread in sleep, and in such cases InterruptedException is thrown.

Java Thread.sleep Example

Here is an example program where Thread.sleep() is used to pause the main thread execution for 2 seconds (2000 milliseconds):

package com.journaldev.threads; public class ThreadSleep  public static void main(String[] args) throws InterruptedException  long start = System.currentTimeMillis(); Thread.sleep(2000); System.out.println("Sleep time in ms = " + (System.currentTimeMillis() - start)); > > 

First, this code stores the current system time in milliseconds. Then it sleeps for 2000 milliseconds. Finally, this code prints out the new current system time minus the previous current system time:

Output
Sleep time in ms = 2005

Notice that this difference is not precisely 2000 milliseconds. This is due to how Thread.sleep() works and the operating system-specific implementation of the thread scheduler.

Conclusion

In this article, you learned about Java’s Thread.sleep() .

Continue your learning with more Java tutorials.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Thread sleep примеры java

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Оцените статью