Implementing the Runnable Interface
The following program shows how to implement MyRunnable
without having to extend the Thread
class:
MyRunnable
class MyRunnable implements Runnable {
String name;
public static void main(String args[]) {
Thread threadA = new Thread(new MyRunnable("A"));
Thread threadB = new Thread(new MyRunnable("B"));
threadA.start();
threadB.start();
while (threadA.isAlive() || threadB.isAlive()) {
Thread.currentThread().yield();
}
MyObject.displayResult();
}
public MyRunnable(String name) {
this.name = name;
}
public void run() {
for (int n = 0; n < 20; n++) {
try {
Thread.sleep((int)(Math.random() * 10.0));
}
catch (InterruptedException e) {}
MyObject.update(name);
}
}
}
class MyObject {
static String result = "";
public static void update(String name) {
result += name;
}
public static void displayResult() {
System.out.println(result);
}
}
Program output:
BBABABABAABABBABABBAABBABBAABBABAAAAA