Write A Program That Executes Two Threads. One Thread Displays “Thread1” Every 1000 Milliseconds, And The Other Displays “Thread2” Every 2000 Milliseconds. Create The Threads By Extending The Thread Class
Before demonstrate the program we will understand the concept of threads.
In Java, a thread is a lightweight unit of execution that can run concurrently with other threads within the same program. Each thread has its own call stack and program counter, which allows it to execute independently of other threads.
Threads can be used to perform tasks in parallel, which can improve the performance and responsiveness of your program. For example, you might use threads to perform long-running calculations or to handle user input while other tasks are being performed.
There are two ways to create a thread in Java: by extending the `Thread` class or by implementing the `Runnable` interface.
To create a thread by extending the `Thread` class, you define a new class that extends `Thread` and overrides its `run()` method. This method contains the code that will be executed when the thread is started. Here's an example:
class MyThread extends Thread { public void run() { // Code to be executed in this thread }}
To start this thread, you create an instance of your custom `MyThread` class and call its `start()` method:
MyThread myThread = new MyThread();myThread.start();
Alternatively, you can create a thread by implementing the `Runnable` interface. This involves defining a class that implements `Runnable` and provides an implementation for its `run()` method. Here's an example:
class MyRunnable implements Runnable { public void run() { // Code to be executed in this thread }}
To start this thread, you create an instance of your custom `MyRunnable` class and pass it as an argument to the constructor of the `Thread` class. You then call the `start()` method on the resulting `Thread` object:
MyRunnable myRunnable = new MyRunnable();Thread myThread = new Thread(myRunnable);myThread.start();
class Thread1 extends Thread { public void run() { while (true) { System.out.println("Thread1"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }}
class Thread2 extends Thread { public void run() { while (true) { System.out.println("Thread2"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } }}
public class Main { public static void main(String[] args) { new Thread1().start(); new Thread2().start(); }}
Thread1
Thread2
Thread1
Thread2
Thread1
Thread1
Thread2
Thread1
Thread1
Thread2
Thread1
Thread1
Thread2
Thread1
Thread1
Thread2
Thread1
Thread1
Thread2
Thread1
Thread1
Thread2
Thread1