summary refs log tree commit diff stats
path: root/java/code/ThreadsExample.java
diff options
context:
space:
mode:
Diffstat (limited to 'java/code/ThreadsExample.java')
-rw-r--r--java/code/ThreadsExample.java36
1 files changed, 36 insertions, 0 deletions
diff --git a/java/code/ThreadsExample.java b/java/code/ThreadsExample.java
new file mode 100644
index 0000000..33ad571
--- /dev/null
+++ b/java/code/ThreadsExample.java
@@ -0,0 +1,36 @@
+class NumberRunnable implements Runnable {
+    public void run() {
+        for (int i = 1; i <= 10; i++) {
+            System.out.println(Thread.currentThread().getId() + " - " + i);
+        }
+    }
+}
+
+class NumberThread extends Thread {
+    public void run() {
+        for (int i = 1; i <= 10; i++) {
+            System.out.println(Thread.currentThread().getId() + " - " + i);
+        }
+    }
+}
+
+public class ThreadsExample {
+    public static void main(String[] args) {
+        Thread[] threads = new Thread[6];
+
+        // Creating three threads using NumberThread class (inheriting Thread)
+        for (int i = 0; i < 3; i++) {
+            threads[i] = new NumberThread();
+        }
+
+        // Creating three threads using NumberRunnable class (implementing Runnable)
+        for (int i = 3; i < 6; i++) {
+            threads[i] = new Thread(new NumberRunnable());
+        }
+
+        // Starting all threads
+        for (Thread thread : threads) {
+            thread.start();
+        }
+    }
+}