Name: Ajay Chauhan
Roll NO: 2400290119001
Ssubject: object oriented programming with java
Lab: 7
1. WAP to Create a class MyThread derived from Thread class and
override the run method. Create a class ThreadDemo having a
main method. Create 2 objects of MyThread class and observe the
behavior of threads.
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(getName() + " - Count: " + i);
try {
Thread.sleep(500); // pause for visibility
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.setName("Thread-1");
t2.setName("Thread-2");
t1.start();
t2.start();
}
}
Output
Thread-1 - Count: 1
Thread-2 - Count: 1
Thread-1 - Count: 2
Thread-2 - Count: 2
Thread-1 - Count: 3
Thread-2 - Count: 3
...
2. WAP to Assign different priorities to the 2 threads and observe
the behaviour.
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println(getName() + " (Priority: " + getPriority() + ") -
Iteration: " + i);
try {
Thread.sleep(300);
} catch (InterruptedException e) {
System.out.println(e);
public class ThreadPriorityDemo {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.setName("LowPriorityThread");
t2.setName("HighPriorityThread");
t1.setPriority(Thread.MIN_PRIORITY); // 1
t2.setPriority(Thread.MAX_PRIORITY); // 10
t1.start();
t2.start();
Output
HighPriorityThread (Priority: 10) - Iteration: 1
LowPriorityThread (Priority: 1) - Iteration: 1
HighPriorityThread (Priority: 10) - Iteration: 2
LowPriorityThread (Priority: 1) - Iteration: 2
...