Commit 26b2d9f2 authored by drnull03's avatar drnull03

Initial commit

parents
File added
// MyThreadExample.java
// Method 1: Extending the Thread class
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread running: " + i);
try {
Thread.sleep(500); // sleep for 0.5 second
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}
}
}
}
// Method 2: Implementing Runnable interface
class MyRunnable implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Runnable running: " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println("Runnable interrupted");
}
}
}
}
public class MyThreadExample {
public static void main(String[] args) {
// Create thread using Thread subclass
MyThread t1 = new MyThread();
// Create thread using Runnable interface
Thread t2 = new Thread(new MyRunnable());
// Start both threads
t1.start();
t2.start();
System.out.println("Main thread finished starting others!");
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment