Uploaded by Visheshh

RA2211051010029 APP Week7

advertisement
Vishesh Jain RA2211051010029 APP Tutorial Assignment- WEEK 7_AC2 Section
Q1
import java.util.Random;
class RandomNumberGenerator implements Runnable {
private final int iterations;
private final int minRange;
private final int maxRange;
private final Random random = new Random();
public RandomNumberGenerator(int iterations, int minRange, int
maxRange) {
this.iterations = iterations;
this.minRange = minRange;
this.maxRange = maxRange;
}
@Override
public void run() {
for (int i = 0; i < iterations; i++) {
int randomNumber = random.nextInt(maxRange - minRange + 1) +
minRange;
System.out.println("Generated: " + randomNumber);
if (randomNumber % 2 == 0) {
SecondThread.computeAndPrintSquare(randomNumber);
} else {
ThirdThread.computeAndPrintCube(randomNumber);
}
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
class SecondThread {
public static void computeAndPrintSquare(int number) {
int square = number * number;
System.out.println("Square: " + square);
}
}
class ThirdThread {
public static void computeAndPrintCube(int number) {
int cube = number * number * number;
System.out.println("Cube: " + cube);
}
}
public class q1 {
public static void main(String[] args) {
int iterations = 10; // You can change the number of iterations
int minRange = 1;
// Minimum value for random number generation
int maxRange = 100; // Maximum value for random number generation
Thread randomGeneratorThread = new Thread(new
RandomNumberGenerator(iterations, minRange, maxRange));
randomGeneratorThread.start();
}
}
OUTPUT:-
Q2)
class UserThread extends Thread {
@Override
public void run() {
try {
System.out.println("User Thread is running.");
Thread.sleep(1000); // Sleep for 1 second
System.out.println("User Thread has finished.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class q2 {
public static void main(String[] args) {
UserThread userThread = new UserThread();
Thread mainThread = Thread.currentThread();
userThread.start(); // Start the user thread
try {
System.out.println("Main Thread is running.");
Thread.sleep(1000); // Sleep for 1 second
System.out.println("Main Thread has finished.");
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
userThread.join(); // Wait for the user thread to finish
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Q3)
class MyThread extends Thread {
public MyThread(String name) {
super(name);
}
@Override
public void run() {
try {
System.out.println(getName() + " is sleeping for 5 seconds.");
Thread.sleep(5000); // Sleep for 5 seconds
System.out.println(getName() + " woke up after 5 seconds.");
String newName = getName() + "_Updated";
setName(newName); // Change the name of the thread
System.out.println("Thread name changed to: " + getName());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public class q3 {
public static void main(String[] args) {
MyThread myThread = new MyThread("MyThread");
myThread.start();
}
}
OUTPUT:-
q4)
class MyThread extends Thread {
public MyThread(String name) {
super(name);
}
@Override
public void run() {
try {
for (int i = 5; i >= 1; i--) {
System.out.println(getName() + " is sleeping for " + i + "
seconds.");
Thread.sleep(6000); // Sleep for 6 seconds
}
System.out.println(getName() + " finished.");
String newName = getName() + "_Updated";
setName(newName); // Change the name of the thread
System.out.println("Thread name changed to: " + getName());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public class q4 {
public static void main(String[] args) {
MyThread myThread = new MyThread("MyThread");
myThread.start();
}
}
OUTPUT:-
Q5)
public class q5 {
public static void main(String[] args) {
// Creating and starting the user thread
Thread userThread = new Thread(new UserRunnable());
userThread.start();
// Creating and starting the main thread
Thread mainThread = Thread.currentThread();
new MainRunnable(mainThread).start();
}
}
class UserRunnable implements Runnable {
@Override
public void run() {
try {
Thread.sleep(1000); // Sleep for 1 second
System.out.println("User Thread: After 1 second");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class MainRunnable extends Thread {
private Thread mainThread;
public MainRunnable(Thread mainThread) {
this.mainThread = mainThread;
}
@Override
public void run() {
try {
Thread.sleep(1000); // Sleep for 1 second
System.out.println("Main Thread: After 1 second");
mainThread.join(); // Wait for the user thread to finish
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
OUTPUT:-
Q6)
class Printer {
private int currentJobNumber = 1;
public synchronized void print(String job) {
int jobNumber = Integer.parseInt(job);
// Wait until it's the turn of this job
while (jobNumber != currentJobNumber) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
// Print the job
System.out.println("Printing Job: " + job);
// Increment the job number
currentJobNumber++;
// Notify all waiting threads
notifyAll();
}
}
class PrintJob implements Runnable {
private static Printer printer = new Printer();
private String jobNumber;
public PrintJob(String jobNumber) {
this.jobNumber = jobNumber;
}
@Override
public void run() {
printer.print(jobNumber);
}
}
public class q6 {
public static void main(String[] args) {
Thread[] threads = new Thread[10]; // Create 10 threads for 10
jobs
// Start the threads with job numbers from 1 to 10
for (int i = 0; i < 10; i++) {
threads[i] = new Thread(new PrintJob(Integer.toString(i +
1)));
threads[i].start();
}
// Wait for all threads to complete
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println("All jobs have been completed.");
}
}
OUTPUT:-
Q7)
class CountThread extends Thread {
private String input;
private int count;
public CountThread(String input) {
this.input = input;
}
public int getCount() {
return count;
}
@Override
public void run() {
if (this.getName().equals("ThreadA")) {
// Count digits
count = countDigits(input);
System.out.println("ThreadA:" + count);
} else if (this.getName().equals("ThreadB")) {
// Count alphabetic characters
count = countAlphabetic(input);
System.out.println("ThreadB:" + count);
}
}
private int countDigits(String input) {
int digitCount = 0;
for (char c : input.toCharArray()) {
if (Character.isDigit(c)) {
digitCount++;
}
}
return digitCount;
}
private int countAlphabetic(String input) {
int alphabeticCount = 0;
for (char c : input.toCharArray()) {
if (Character.isAlphabetic(c)) {
alphabeticCount++;
}
}
return alphabeticCount;
}
}
public class q7 {
public static void main(String[] args) {
String k = "Hello123World456";
CountThread threadA = new CountThread(k);
CountThread threadB = new CountThread(k);
threadA.setName("ThreadA");
threadB.setName("ThreadB");
threadA.start();
threadB.start();
try {
threadA.join();
threadB.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
OUTPUT:-
q8)
import java.util.Scanner;
class UserThreadPriority extends Thread {
private String k;
private char c;
public UserThreadPriority(String name) {
super(name);
}
public void setK(String k) {
this.k = k;
}
public void setC(char c) {
this.c = c;
}
@Override
public void run() {
System.out.println("Thread " + this.getName() + " received k = " +
k + " and c = " + c);
}
}
public class q8 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Create thread objects with names
UserThreadPriority threadobj1 = new UserThreadPriority("ThreadA");
UserThreadPriority threadobj2 = new UserThreadPriority("ThreadB");
// Get input from the user
System.out.print("Enter a String (k): ");
String userInputK = scanner.nextLine();
System.out.print("Enter a Character (c): ");
char userInputC = scanner.next().charAt(0);
// Set the values for the thread objects
threadobj1.setK(userInputK);
threadobj1.setC(userInputC);
threadobj2.setK(userInputK);
threadobj2.setC(userInputC);
// Start the threads
threadobj1.start();
threadobj2.start();
}
}
OUTPUT:-
Q9)
class CustomThread extends Thread {
private long sleepDuration;
public CustomThread(long sleepDuration) {
this.sleepDuration = sleepDuration;
}
@Override
public void run() {
try {
System.out.println("Thread " + this.getId() + " is sleeping
for " + sleepDuration + " milliseconds.");
Thread.sleep(sleepDuration);
System.out.println("Thread " + this.getId() + " has finished
sleeping.");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public class q9 {
public static void main(String[] args) {
long[] sleepDurations = {10, 20, 50, 70, 100};
for (long duration : sleepDurations) {
CustomThread thread = new CustomThread(duration);
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
OUTPUT:-
Q10)
class PriorityThread extends Thread {
public PriorityThread(String name, int priority) {
super(name);
setPriority(priority);
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println(getName() + " is running (Iteration " + (i
+ 1) + ")");
try {
Thread.sleep(100); // Simulate some work
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
public class q10 {
public static void main(String[] args) {
PriorityThread thread1 = new PriorityThread("Thread 1 (Low
Priority)", Thread.MIN_PRIORITY);
PriorityThread thread2 = new PriorityThread("Thread 2 (Low
Priority)", Thread.MIN_PRIORITY);
PriorityThread thread3 = new PriorityThread("Thread 3 (Normal
Priority)", Thread.NORM_PRIORITY);
PriorityThread thread4 = new PriorityThread("Thread 4 (High
Priority)", Thread.MAX_PRIORITY);
PriorityThread thread5 = new PriorityThread("Thread 5 (High
Priority)", Thread.MAX_PRIORITY);
thread4.setDaemon(true); // Mark thread4 as a daemon thread
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
try {
thread1.join();
thread2.join();
thread3.join();
thread5.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Main thread has finished.");
}
}
OUTPUT:-
Download