과제
2022.07.11 / Hw1

                          Thread를 이용해서 현재 시간을 1초에 한번씩 출력하는 
      프로그램을 작성 하세요

 

 

의도

스레드 사용

sleep()메소드 사용

 

 

깃허브

https://github.com/kindacool/Hw/blob/main/HW20220711/TimeThreadHw.java

 

GitHub - kindacool/Hw

Contribute to kindacool/Hw development by creating an account on GitHub.

github.com

 

 

코드

package p2022_07_11;

import java.text.SimpleDateFormat;
import java.util.Date;

public class TimeThreadHw extends Thread {

	@Override
	public void run() {

		while (true) {
			Date d = new Date();
			SimpleDateFormat dd = new SimpleDateFormat("yyyy년 MM월 dd일 HH:mm:ss");
			System.out.println(dd.format(d));

			try {
				sleep(1000);
			} catch (InterruptedException ie) {
				System.out.println(ie.toString());
			}

		}
	}

	public static void main(String[] args) {

		TimeThreadHw tth = new TimeThreadHw();
		tth.start();

	}

}

 

 

출력

 

 

강사님 코드

package p2022_07_12;

import java.text.SimpleDateFormat;
import java.util.Date;

public class ThreadEx implements Runnable {

	@Override
	public void run() {
		// TODO Auto-generated method stub
		SimpleDateFormat sf = new SimpleDateFormat("yyyy년 MM월 dd일 HH:mm:ss");

		while (true) {
			try {
				Date d = new Date();
				System.out.println(sf.format(d));
				Thread.sleep(1000);
			} catch (Exception e) {
			}
		}
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ThreadEx tx = new ThreadEx();
		Thread t = new Thread(tx);
		t.start();
	}

}

+ Recent posts