import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * {@link <a href=
 * "https://[Log in to view URL]"
 * target= "_blank"></a>}
 * 
 * @author itammb ( Italia Massimiliano Buscati )
 * @version JDK 1.15
 *
 */
class Main {
	public static class Task implements Runnable {
		private String task;
		private SimpleDateFormat ft;

		public Task(String task) {
			this.task = task;
			ft = new SimpleDateFormat("hh:mm:ss");
		}

		@Override
		public void run() {
			try {
				for (int i = 0; i <= 3; i++) {
					if (i == 0)
						log("INIT");
					else
						log("EXECUTE - STEP-" + i);

					Thread.sleep(1000);
				}

				log("COMPLETE");
			} catch (InterruptedException ie) {
				log("KILL");
				ie.printStackTrace();
			}
		}

		private void log(String status) {
			System.out.println(task + " - " + status + " - " + ft.format(new Date()));
		}

		@Override
		public String toString() {
			return "Task [task=" + task + ", hashCode()=" + hashCode() + "]";
		}
	}

	private static class UniTest {
		/**
		 * @see Executors#newScheduledThreadPool(int)
		 * @see ScheduledExecutorService#schedule(Runnable, long, TimeUnit)
		 */
		public void simulateScheduledService() throws InterruptedException, ExecutionException {
			List<FutureTask<String>> buffer = new ArrayList<FutureTask<String>>();

			ScheduledExecutorService pool = Executors.newScheduledThreadPool(4);

			for (int i = 0; i < 10; i++) {
				FutureTask<String> task = new FutureTask<String>(new Task("task " + i), "RESULT Object ");
				buffer.add(task);
				// manda in esecuzione la computazione dopo i secondi
				pool.schedule(task, i, TimeUnit.SECONDS);
			}

			Thread.sleep(10000); // attende 10 secondi

			for (FutureTask<String> task : buffer)
				if ((System.currentTimeMillis() % 2) == 0)
					// Se l'attività è già stata avviata, il parametro mayInterruptIfRunning = true
					// determina se il thread che esegue la computazione deve essere interrotto
					// nel tentativo di fermare l'attività.
					task.cancel(true);
				else
					Thread.sleep(2);

			shutdown(pool);

			executeStatus(buffer);
		}

		private void shutdown(ExecutorService pool) throws InterruptedException {
			pool.shutdown();

			while (!pool.isTerminated())
				Thread.sleep(2);

			System.out.println("SHUTDOWN - OK");
		}

		/**
		 * @see FutureTask#isCancelled()
		 * @see FutureTask#get()
		 * 
		 */
		private void executeStatus(List<FutureTask<String>> buffer) throws InterruptedException, ExecutionException {

			for (FutureTask<String> task : buffer)
				if (task.isCancelled())
					System.out.println(task.toString() + " - CANCELLED");
				else {
					System.out.println(task.toString() + " - " + task.get());
				}
		}

		/**
		 * @see Executors#newScheduledThreadPool(int)
		 * 
		 */
		public void simulateScheduledWithFixedDelay() throws InterruptedException, ExecutionException {
			ScheduledExecutorService pool = Executors.newSingleThreadScheduledExecutor();

			// sottomette un task periodico che si attiva prima volta dopo il ritardo
			// iniziale [ 1 secondo ] e successivamente
			// dopo [ 3 secondi ] tra la fine di un'esecuzione e l'inizio della successiva
			ScheduledFuture<?> scheduled = pool.scheduleWithFixedDelay(new Task("task " + 1), 1, 3, TimeUnit.SECONDS);

			Thread.sleep(20000);

			shutdown(pool);
			scheduledStatus(scheduled);
		}

		private void scheduledStatus(ScheduledFuture<?> task) throws InterruptedException, ExecutionException {

			if (task.isDone())
				System.out.println(task.toString() + " - OK ");
			else {
				System.out.println(task.toString() + " - ERROR ");
			}
		}
	}

	public static void main(String args[]) throws InterruptedException, ExecutionException, TimeoutException {
		// Unit test - sottomette un task dopo un determinato ritardo
		new UniTest().simulateScheduledService();

		// Unit test - sottomette un task con un ritardo periodico
		new UniTest().simulateScheduledWithFixedDelay();
	}
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: