xxxxxxxxxx
public class CountDown {
// A Java code that creates 5 parallel tasks
// performing countdown from 5 to 0
public static void main(String[] args) {
CountDown application = new CountDown();
application.start();
}
// Method for spawning 5 parallel threads of execution
public void start() {
for(int i=1; i<=5; i++)
new Thread(new CountDownHandler(5, i)).start();
}
// Utility class for handling count down per thread
// that implements the Runnable interface
private class CountDownHandler implements Runnable {
private int id;
private int counter;
public CountDownHandler(int counter, int id) {
this.counter = counter;
this.id = id;
}
public String status() {
return "id#" + id + " " +
((counter >= 0) ? counter : "LiftOff!");
}
public void run() {
while(counter >= -1) {
System.out.println(status());
counter--;
try {
Thread.sleep(1000);
} catch(Exception e) {
}
}
}
}
}
xxxxxxxxxx
// Java Program to implement Runnable interface
// Importing FileNotFound class from
// input output classes bundle
import java.io.FileNotFoundException;
import java.util.concurrent.*;
// Class
// Implementing the Runnable interface
class RunnableImpl implements Runnable {
public void run()
{
System.out.println("Hello World from a different thread than Main");
}
}
public class RunnableExample{
static ExecutorService executor = Executors.newFixedThreadPool(2);
public static void main(String[] args){
// Creating and running runnable task using Thread class
RunnableImpl task = new RunnableImpl();
Thread thread = new Thread(task);
thread.start();
// Creating and running runnable task using Executor Service.
executor.submit(task);
}
}
xxxxxxxxxx
@FunctionalInterface
public interface Runnable {
public abstract void run();
}