java

[java] Executor 클래스를 이용한 멀티 스레드 실행 예제

hs_seo 2019. 4. 19. 16:22

Executors 클래스를 이용한 멀티 스레드 실행 예제입니다. 

 

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class SchedulerExecutorSample {

	public static void main(String[] args) {

		// scheduleAtFixedRate(실행가능객체, 지연시간, 주기, 단위)
		Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new TimeRunnable(), 0, 1, TimeUnit.SECONDS);
		Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new TimeRunnable(), 0, 2, TimeUnit.SECONDS);
		Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new TimeRunnable(), 0, 3, TimeUnit.SECONDS);
		Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new TimeRunnable(), 0, 4, TimeUnit.SECONDS);
		
	}
}

class TimeRunnable extends Thread {
	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.sss");
	
	@Override
	public void run() {
		System.out.printf("[%s] %s\n", Thread.currentThread().getName(), format.format(new Date(System.currentTimeMillis())));
	}
}
반응형