찾다
Javajava지도 시간자바의 타이머

자바의 타이머

Aug 30, 2024 pm 03:53 PM
java

Java의 타이머는 Java에서 사용할 수 있습니다. util 패키지는 객체 클래스를 확장하고 직렬화 가능 및 복제 가능 인터페이스를 구현합니다. 타이머 클래스에는 타이밍 관련 활동을 수행하는 데 사용되는 메서드가 포함되어 있습니다. Java의 타이머 클래스는 시간 관련 작업 스케줄링을 수행하는 데 사용됩니다. Java 스레드는 Timer 클래스의 메서드를 사용하여 일정 시간이 지난 후 코드 섹션을 실행하거나 미리 정의된 일정 시간이 지난 후 코드를 반복적으로 실행하는 등의 작업을 예약합니다. 각 Timer 개체는 스레드와 관련된 모든 작업을 실행하는 별도의 백그라운드 실행 스레드에 바인딩됩니다. Java의 타이머 클래스는 스레드로부터 안전합니다. 즉, 한 번에 하나의 스레드만 Timer 클래스 메서드를 실행할 수 있습니다. 또한 Timer 클래스는 작업을 저장하기 위한 기본 데이터 구조로 바이너리 힙을 사용합니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

Java의 타이머 구문

다음은 Java에서 Timer 클래스를 사용하는 방법에 대한 기본 구문입니다.

구문:

// create a class extending TimerTask
class TimerHelper extends TimerTask
{
//define run method
public void run()
{
// Write Code to be executed by Timer
}
}
class MainClass{
public static void main(String[] args)
{
//create timer instance
Timer timer = new Timer();
// create Timer class instance
TimerTask task = new TimerHelper ();
// call timer method
timer.schedule(task, 3000,6000);
//first argument is timer object
// second argument is time in milliseconds after which the code will be first executed
// Third argument is time in milliseconds after which the code will be executed regularly.
}
}

위 구문 설명: 구문은 Java에서 Timer 클래스가 사용되는 방식을 보여줍니다. 타이머 클래스를 사용하려면 TimerTask를 확장하는 클래스를 만들고 그 안에 run 메서드를 정의해야 합니다. run 메소드에는 시간에 따라 실행되어야 하는 로직이 포함되어 있습니다. 다음은 Timer 클래스 선언입니다.

public  class Timer extends Object
implements Serializable, Cloneable

Java의 Timer 클래스 메서드

이제 Java Timer 클래스에서 사용할 수 있는 다양한 메소드와 필드가 무엇인지 살펴보겠습니다. Timer 클래스에서 일반적으로 사용되는 메소드 목록은 다음과 같습니다.

Method Name Description
public void schedule(TimerTask task, Date date) Schedules a task to be executed on the defined date.
public  void schedule (TimerTask task, Date firstTime, long timeperiod) The first argument is TimerTask to be executed; the second argument is the time after which the task is executed for the first time, and the third argument is seconds in milliseconds after which task will be executed regularly.
public  int purge() Used for removing all canceled tasks from the timer’s queue.
public void cancel() Cancel’s the timer.
public void schedule(TimeTask task, long delay) Schedules the task to be executed after the specified time in milliseconds.
public void schedule(TimeTask task, long delay, long period) The first argument is TimerTask to be executed; the second argument is the time in milliseconds after which task is executed for the first time, and the third argument is seconds in milliseconds after which task will be executed regularly.
public  void scheduleAtFixedRate(TimerTask task, Date firstTime, long timeperiod) The first argument is TimerTask to be executed; the second argument is the time after which the task is executed for the first time, and the third argument is seconds in milliseconds after which the task will be executed regularly.
public void scheduleAtFixedRate (TimeTask task, long delay, long period) The first argument is TimerTask to be executed; the second argument is the time in milliseconds after which task is executed for the first time, and the third argument is seconds in milliseconds after which task will be executed regularly.
메서드 이름 설명 공개 무효 일정(TimerTask 작업, 날짜 날짜) 정의된 날짜에 작업이 실행되도록 예약합니다. 공개  무효 일정(TimerTask 작업, 날짜 최초 시간, 긴 기간) 첫 번째 인수는 실행할 TimerTask입니다. 두 번째 인수는 작업이 처음으로 실행된 후의 시간이고, 세 번째 인수는 이후 작업이 정기적으로 실행되는 초(밀리초)입니다. 공개  int purge() 타이머 대기열에서 취소된 모든 작업을 제거하는 데 사용됩니다. 공개 무효 취소() 타이머를 취소하세요. 공개 무효 일정(TimeTask 작업, 긴 지연) 지정된 시간(밀리초) 후에 작업이 실행되도록 예약합니다. 공개 무효 일정(TimeTask 작업, 장기 지연, 장기) 첫 번째 인수는 실행할 TimerTask입니다. 두 번째 인수는 작업이 처음으로 실행된 후의 시간(밀리초)이고, 세 번째 인수는 작업이 정기적으로 실행된 후의 시간(밀리초)입니다. public  void ScheduleAtFixedRate(TimerTask 작업, 날짜 firstTime, 긴 기간) 첫 번째 인수는 실행할 TimerTask입니다. 두 번째 인수는 작업이 처음으로 실행된 후의 시간이고, 세 번째 인수는 작업이 정기적으로 실행된 이후의 초(밀리초)입니다. public void ScheduleAtFixedRate(TimeTask 작업, 장기 지연, 장기) 첫 번째 인수는 실행할 TimerTask입니다. 두 번째 인수는 작업이 처음으로 실행된 후의 시간(밀리초)이고, 세 번째 인수는 작업이 정기적으로 실행된 후의 시간(밀리초)입니다.

From the above-stated methods, we have found two methods that are similar in working but different in the name; they are schedule and scheduleAtFixedRate. The difference between the two is that in the case of fixed-rate execution, each execution is scheduled in accordance with the initial execution. If there is a delay in execution, then two or more executions will occur in quick succession to overcome the delay.

Constructors in Timer Class

The timer class contains four constructors for instantiating timer object.

  • Timer(): Creates a new Timer Object.
  • Timer(boolean isDaemon): Creates a timer object with a corresponding thread specified to run as a daemon.
  • Timer(String name): Creates a timer object with a corresponding thread name.
  • Timer(String name, boolean isDaemon): This method is a combination of the above two constructors.

One of the above four listed constructors can be called depending on our requirements.

Examples of Implementing Timer in Java

Below is the example of Timer in Java:

Example #1

To start things, let us see a basic example of Timer class. In this example, we will demonstrate the use of the schedule method of the Timer class.

Code:

package com.edubca.timer;
import java.util.Timer;
import java.util.TimerTask;
class TimerHelper extends TimerTask
{
public static int counter = 0;
public void run()
{
counter++;
System.out.println("Timer run Number " + counter);
}
}
public class Main
{
public static void main(String[] args)
{
Timer timer = new Timer();
TimerTask timerhelper = new TimerHelper();
timer.schedule(timerhelper, 3000, 2000);
}
}

Explanation of the above code: The above code will execute the run method for the first time after 3 seconds as the first argument is 3000, and after every 2 seconds, the run method will be executed regularly. Here is the output that will be displayed:

Output:

자바의 타이머

Example #2

In this example, we will see how to terminate a timer thread after a given number of timer runs.

Code:

package com.edubca.timer;
import java.util.Timer;
import java.util.TimerTask;
class TimerHelper extends TimerTask
{
public static int counter = 0;
public void run()
{
counter++;
if(counter ==3){
this.cancel();
System.out.println("Now Cancelling Thread!!!!!");
return;
}
System.out.println("Timer run Number " + counter);
}
}
public class Demo
{
public static void main(String[] args)
{
Timer timer = new Timer();
TimerTask helper = new TimerHelper();
helper.schedule(task, 3000, 2000);
}
}

In the above example, the timer will cancel after the three times run method is called using the timer class’s cancel method.

Output:

자바의 타이머

위 내용은 자바의 타이머의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
고급 Java 프로젝트 관리, 구축 자동화 및 종속성 해상도에 Maven 또는 Gradle을 어떻게 사용합니까?고급 Java 프로젝트 관리, 구축 자동화 및 종속성 해상도에 Maven 또는 Gradle을 어떻게 사용합니까?Mar 17, 2025 pm 05:46 PM

이 기사에서는 Java 프로젝트 관리, 구축 자동화 및 종속성 해상도에 Maven 및 Gradle을 사용하여 접근 방식과 최적화 전략을 비교합니다.

적절한 버전 및 종속성 관리로 Custom Java 라이브러리 (JAR Files)를 작성하고 사용하려면 어떻게해야합니까?적절한 버전 및 종속성 관리로 Custom Java 라이브러리 (JAR Files)를 작성하고 사용하려면 어떻게해야합니까?Mar 17, 2025 pm 05:45 PM

이 기사에서는 Maven 및 Gradle과 같은 도구를 사용하여 적절한 버전 및 종속성 관리로 사용자 정의 Java 라이브러리 (JAR Files)를 작성하고 사용하는 것에 대해 설명합니다.

카페인 또는 구아바 캐시와 같은 라이브러리를 사용하여 자바 애플리케이션에서 다단계 캐싱을 구현하려면 어떻게해야합니까?카페인 또는 구아바 캐시와 같은 라이브러리를 사용하여 자바 애플리케이션에서 다단계 캐싱을 구현하려면 어떻게해야합니까?Mar 17, 2025 pm 05:44 PM

이 기사는 카페인 및 구아바 캐시를 사용하여 자바에서 다단계 캐싱을 구현하여 응용 프로그램 성능을 향상시키는 것에 대해 설명합니다. 구성 및 퇴거 정책 관리 Best Pra와 함께 설정, 통합 및 성능 이점을 다룹니다.

캐싱 및 게으른 하중과 같은 고급 기능을 사용하여 객체 관계 매핑에 JPA (Java Persistence API)를 어떻게 사용하려면 어떻게해야합니까?캐싱 및 게으른 하중과 같은 고급 기능을 사용하여 객체 관계 매핑에 JPA (Java Persistence API)를 어떻게 사용하려면 어떻게해야합니까?Mar 17, 2025 pm 05:43 PM

이 기사는 캐싱 및 게으른 하중과 같은 고급 기능을 사용하여 객체 관계 매핑에 JPA를 사용하는 것에 대해 설명합니다. 잠재적 인 함정을 강조하면서 성능을 최적화하기위한 설정, 엔티티 매핑 및 모범 사례를 다룹니다. [159 문자]

Java의 클래스로드 메커니즘은 다른 클래스 로더 및 대표 모델을 포함하여 어떻게 작동합니까?Java의 클래스로드 메커니즘은 다른 클래스 로더 및 대표 모델을 포함하여 어떻게 작동합니까?Mar 17, 2025 pm 05:35 PM

Java의 클래스 로딩에는 부트 스트랩, 확장 및 응용 프로그램 클래스 로더가있는 계층 적 시스템을 사용하여 클래스로드, 링크 및 초기화 클래스가 포함됩니다. 학부모 위임 모델은 핵심 클래스가 먼저로드되어 사용자 정의 클래스 LOA에 영향을 미치도록합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기