Simple Thread Sample using Runnable interface Implementation
Here the sample code explains how to implement Runnable interface to create threads in Java. Please see previous post to know How to create threads by extending Thread class.
class 1: This MyPrinter is class, has method print() which will be called from multiple threads and is shared across multiple threads.
public class MyPrinter {public void print(String pName,int i)
{
System.out.println(pName+"_"+i);
}
}
class 2: This is the class which implements Runnable interface and overrides the run methods, the job/task you want to perform in thread should be put inside the methods run().
public class Runnable1 implements Runnable {private MyPrinter printer;
Runnable1(MyPrinter printer) {
this.printer = printer;
}
public void run() {
int i = 0;
while (i < 200) {
printer.print("Runnable_1", i);
i++;
}
}
}
class 2: This is the another same as above class which implements Runnable interface and overrides the run methods, the another job/task you want to perform in thread should be put inside the methods run().
public class Runnable2 implements Runnable {private MyPrinter printer;
Runnable2(MyPrinter printer) {
this.printer = printer;
}
public void run() {
int i = 0;
while (i < 200) {
printer.print("Runnable_2", i);
i++;
}
}
}
class 4: The main class to be executed is described here. Please see the difference here, unlike instantiating the Runnable and calling start() method on it, we instantiate Runnable1 and Runnable2 objects and passing those instance as argument to another Thread objects. So these are the real objects.
public class SimpleThreadTest {
public static void main(String[] args) {
MyPrinter p = new MyPrinter();
Runnable1 t1= new Runnable1(p);
Runnable2 t2= new Runnable2(p);
new Thread(t1).start();
new Thread(t2).start();
}
}