[JAVA] Timer, TimerTask, Thread 이용하기

개요

10초 후에 A 값을 출력하고 B 값을 출력하고 싶을 때 프로그램 객체에서 이 코드를 사용할 수 있다.

Using Timer and TimerTask 

프로그래밍하기 전에 준비

import java.util.TimerTask


Source code

public void onExecute() {

    setAOValue(new BStatusNumeric(100));
    
Timer tmr = new Timer();
TimerTask tmr_task = new TimerTask()
{
    public void run()
    {
        //do it code
        setAOValue(new BStatusNumeric(200));
    }
}
tmr.schedule(tmr_task,5000);
//tmr.schedule(tmr_task,5000,2000) : Operative every two seconds, after 5 seconds.

}// end of onExecute()


결과

이 코드는 출력 100을 먼저 작동하고 5초 후에 출력 200을 출력한다.

스레드 사용

프로그래밍하기 전에 준비

nothing special.


Source code

public void onExecute() 

  throws Exception
{
  setNormal();
}


public void setNormal()
{
  // Create a new thread, with the starting point set as the current program  object.
  Thread thread = new Thread(this, getProgram().getName());
  
  // Start the thread
  thread.start();



public void run()
{
  // This task will take a long time
  {
    System.out.println("started task ["+Thread.currentThread().getName()+"]");
    setAO_01(new BStatusNumeric(11));
    setAO_02(new BStatusNumeric(22));
    setAO_03(new BStatusNumeric(33));
   
    try
    {
      Thread.sleep(10000);
          setAO_01(new BStatusNumeric(100));
          setAO_02(new BStatusNumeric(200));
          setAO_03(new BStatusNumeric(300));
      
    } catch (InterruptedException ie) {
      // Do nothing
      System.out.println(ie);
    }
    System.out.println("ended task ["+Thread.currentThread().getName()+"]");
  }


결과

이 코드는 각각 11,22,33을 먼저 출력하고 5초 후에 100,200,300을 출력한다.


댓글

이 블로그의 인기 게시물

공조설비에 대한 이해

자동제어 기본 교육자료 정리1 DDC 및 설비계통

RS485통신과 데이지체인(DaisyChain) 결선방식