Unit 5 programs
[Link] a programme in Java to demonstrate multithreading in Java.
class MyThread extends Thread {
public void run() {
[Link]("Thread is running");
public class Test {
public static void main(String args[]) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
[Link]();
[Link]();
Output:
Thread is running
Thread is running
2. )Write a programme in Java to demonstrate thread cycle in Java.
class MyThread extends Thread {
public void run() {
[Link]("Thread is in Running state");
try {
[Link](1000); // Thread goes to Waiting/Blocked state
} catch (InterruptedException e) {
[Link](e);
}
[Link]("Thread is back to Running state");
public class ThreadLifeCycle {
public static void main(String args[]) {
MyThread t = new MyThread(); // New State
[Link]("Thread is in New state");
[Link](); // Runnable State
[Link]("Thread is in Runnable state");
Output:
Thread is in New state
Thread is in Runnable state
Thread is in Running state
Thread is back to Running state
3) Explain thread class and runnable interface in Java with example.
class MyThread extends Thread {
public void run() {
[Link]("Thread using Thread class");
public static void main(String args[]) {
MyThread t = new MyThread();
[Link]();
Output: Thread using Thread class
Example using Runnable Interface:
class MyRunnable implements Runnable {
public void run() {
[Link]("Thread using Runnable interface");
public static void main(String args[]) {
MyRunnable obj = new MyRunnable();
Thread t = new Thread(obj);
[Link]();
Output:
Thread using Runnable interfac