|
Previous Next
Implements the Runnable interface
This example is very similar to the previous one except it uses the Runnable interface instead of the Thread class.
There are 2 classes in this program listing, RunnableNum and RunnableSamp. The filename that you save should be RunnableSamp.java because that is where the main class exists and where the public entry point of the program is.
In our constructor for RunnableNum, we will receive an initial numeric value. We will use it to set num1 which will be different for each object created from RunnableNum.
Our main method in the RunnableSamp class will create 3 threads with 3 different initial values, 300, 1000, and 2500. The format of one of the constructors for Thread follows. Note, r1 is an instance of our runnable class and thread1 is the name we're giving to this particular thread.
Thread(Runnable target, String name)
as shown in
Thread th1 = new Thread(r1, "thread1");
In the run method of the Runnable class, we increment this initial value 5 times using the for loop, then we display the values each time. In between each calculation and printing, we sleep for a second.
class RunnableNum implements Runnable {
int num1;
RunnableNum(int num) {
num1 = num;
}
public void run() {
for (int i=0; i<5; i++) {
int num2 = num1 + i;
System.out.println(" num1=" + num1 + " num2=" + num2);
try {
//delay for one second
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
}
}
}
}
public class RunnableSamp {
public static void main(String[] args) {
RunnableNum r1 = new RunnableNum(300);
RunnableNum r2 = new RunnableNum(1000);
RunnableNum r3 = new RunnableNum(2500);
Thread th1 = new Thread(r1, "thread1");
Thread th2 = new Thread(r2, "thread2");
Thread th3 = new Thread(r3, "thread3");
th1.start();
th2.start();
th3.start();
}
}
Previous Next
|