스레드를 누가 실행하고, 얼마나 실행되었는지 편하게 보기 위해 로거를 만들어 보려고 한다.
(실무에서는 보통 로거라는 라이브러리를 씁니당.)
package util;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public abstract class MyLogger { // 추상클래스로 만들어서 직접 생성할 수 없도록 함.
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss.SSS");
public static void log(Object obj) {
String time = LocalDateTime.now().format(formatter);
System.out.printf("%s [%9s] %s\n", time, Thread.currentThread().getName(), obj);
}
}
printf
에서 %s는 문자열을 뜻한다.Object
타입인데, %s
를 사용하면 toString()
을 사용해서 문자열료 변환 후 출력한다.간단한 Main 클래스에서 main 메서드를 만들어 출력하면,
package util;
public abstract class MyLoggerMain {
public static void main(String[] args) {
MyLogger.log("hello Thread");
MyLogger.log(123);
}
}
15:34:48.304 [ main] hello Thread
15:34:48.305 [ main] 123
package thread.start;
import static util.MyLogger.log;
public class ManyThreadMainV1 {
public static void main(String[] args) {
log("main() start");
HelloRunnable runnable = new HelloRunnable();
Thread thread1 = new Thread(runnable);
thread1.start();
Thread thread2 = new Thread(runnable);
thread2.start();
Thread thread3 = new Thread(runnable);
thread3.start();
log("main() end");
}
}
출력 👇
15:43:15.608 [ main] main() start
15:43:15.610 [ main] main() end
Thread-1: run()
Thread-0: run()
Thread-2: run()
Thread-0
, Thread-1
, Thread-2
스레드에 일 시킴HelloRunnable
인스턴스(x001)를 스레드의 실행 작업으로 전달Thread-0
, Thread-1
, Thread-2
는 모두 HelloRunnable
인스턴스에 있는 run()
메서드를 실행