Q1.
Write a Java program to demonstrate the use of sleep() and join() methods in
multithreading.
class SleepJoinDemo extends Thread {
public void run() {
try {
for(int i = 1; i <= 3; i++) {
[Link]("Child Thread: " + i);
[Link](1000);
}
} catch (InterruptedException e) {
[Link](e);
}
}
public static void main(String[] args) throws InterruptedException {
SleepJoinDemo t = new SleepJoinDemo();
[Link]();
[Link]();
[Link]("Main thread finished");
}
}
Q2. Write a Java program to demonstrate thread synchronization using a shared resource.
class Counter {
int count = 0;
synchronized void increment() {
count++;
}
}
class MyThread extends Thread {
Counter c;
MyThread(Counter c) {
this.c = c;
}
public void run() {
for(int i = 1; i <= 1000; i++)
[Link]();
}
}
public class SyncDemo {
public static void main(String[] args) throws InterruptedException {
Counter c = new Counter();
MyThread t1 = new MyThread(c);
MyThread t2 = new MyThread(c);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]("Final Count: " + [Link]);
}
}
Q3. Write a Java program to define an enumeration and display all enumeration constants
using values() method.
enum Day { MON, TUE, WED }
public class EnumDemo {
public static void main(String[] args) {
for(Day d : [Link]()) {
[Link](d);
}
}
}
Q4. Write a Java program to demonstrate autoboxing and unboxing using wrapper classes.
public class WrapperDemo {
public static void main(String[] args) {
int a = 10;
Integer obj = a; // Autoboxing
int b = obj; // Unboxing
[Link](a + " " + obj + " " + b);
}
}