import java.text.SimpleDateFormat;
import java.util.ArrayDeque;
import java.util.Date;
import java.util.Queue;
import java.util.concurrent.Executor;
/**
* {@link <a href=
* "https://[Log in to view URL]"
* target= "_blank"></a>}
*
* @author itammb ( Italia Massimiliano Buscati )
* @version JDK 1.15
*
*/
class Main {
private static class DirectExecutor implements Executor {
@Override
public void execute(Runnable task) {
task.run();
}
}
private static class ThreadForTaskExecutor implements Executor {
@Override
public void execute(Runnable task) {
new Thread(task).start();
}
}
private static class SerialExecutor implements Executor {
private final Queue<Runnable> tasks = new ArrayDeque<>();
private final DirectExecutor executor;
private Runnable activeTask;
SerialExecutor() {
executor = new DirectExecutor();
}
public synchronized void execute(Runnable task) {
tasks.add(() -> {
try {
task.run();
} finally {
scheduleNext();
}
});
if (activeTask == null)
scheduleNext();
}
protected synchronized void scheduleNext() {
// politica di schedulazione
if ((activeTask = tasks.poll()) != null) {
executor.execute(activeTask);
}
}
}
private static class RunnableTask implements Runnable {
private String task;
private SimpleDateFormat ft;
public RunnableTask(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)
System.out.println("INIT - " + task + timeExecute());
else
System.out.println("EXECUTE - " + task + timeExecute());
Thread.sleep(1000);
}
System.out.println(task + " COMPLETE" + timeExecute());
} catch (InterruptedException e) {
System.out.println("KILL - " + task + timeExecute());
}
}
private String timeExecute() {
return " - " + ft.format(new Date());
}
@Override
public String toString() {
return "RunnableTask [task=" + task + ", hashCode()=" + hashCode() + "]";
}
}
private static class UniTest {
/**
* @see Executor#execute(Runnable)
*
*/
public void simulateDirectTask() {
Executor executor = new DirectExecutor();
for (int i = 0; i < 4; i++) {
executor.execute(new RunnableTask("task " + i));
}
}
public void simulateThreadForTask() {
Executor executor = new ThreadForTaskExecutor();
for (int i = 0; i < 4; i++) {
executor.execute(new RunnableTask("task " + i));
}
}
public void simulateScheduledTask() {
Executor executor = new SerialExecutor();
for (int i = 0; i < 4; i++) {
executor.execute(new RunnableTask("task " + i));
}
}
}
public static void main(String args[]) {
// Unit test - esegue istantaneamente i task inviati
new UniTest().simulateDirectTask();
// Unit test - esegue il task in un thread diverso da quello chiamante
// new UniTest().simulateThreadForTask();
// Unit test - esegue una pianificazione dei task inviati
// new UniTest().simulateScheduledTask();
}
}
To embed this project on your website, copy the following code and paste it into your website's HTML: