Page 158 - CTS - CSA TP - Volume 2
P. 158
COMPUTER SOFTWARE APPLICATION - CITS
EXERCISE 103 : Create thread by implementing Runnable
interface
Objectives
At the end of this exercise you shall be able to
• know the creation and execution of threads in Java
• develop Java programs using Super class and Sub class.
Requirements
Tools/Materials
• PC / laptop with windows OS
• SDK software
• Test editor (Visual studio/ subline/ notepad)
Procedure
class MyRunnable implements Runnable {
private String message;
public MyRunnable(String message) {
this.message = message;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + “: “ + message + “ “ + i);
}
}
}
public class ThreadExample {
public static void main(String args[]) {
// Create instances of MyRunnable with different messages
MyRunnable myRunnable1 = new MyRunnable(“Thread 1”);
MyRunnable myRunnable2 = new MyRunnable(“Thread 2”);
// Create Thread objects using MyRunnable instances
Thread t1 = new Thread(myRunnable1, “Thread A”);
Thread t2 = new Thread(myRunnable2, “Thread B”);
// Start the threads
t1.start();
t2.start();
}
}
143
CITS : IT & ITES - Computer Software Application - Exercise 102