0% found this document useful (0 votes)
10 views

Week 7 Assignment

The document contains multiple Java classes demonstrating various aspects of concurrent programming using threads. It includes examples of random number generation, producer-consumer patterns, thread naming, countdowns, and job scheduling with synchronization. Each example illustrates different thread behaviors and synchronization techniques in Java.

Uploaded by

gm2573
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Week 7 Assignment

The document contains multiple Java classes demonstrating various aspects of concurrent programming using threads. It includes examples of random number generation, producer-consumer patterns, thread naming, countdowns, and job scheduling with synchronization. Each example illustrates different thread behaviors and synchronization techniques in Java.

Uploaded by

gm2573
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Week 7 – Tutorial Assignment

CONCURRENT PROGRAMMING PARADIGM: THREAD CLASSES AND METHODS

RA2311026010866

1. import java.util.Random;

class RandomNumberGenerator extends Thread {

private final NumberProcessor processor;

public RandomNumberGenerator(NumberProcessor processor) {

this.processor = processor;

public void run() {

Random random = new Random();

while (true) {

int number = random.nextInt(100); // Generate random integer between 0 and 99

System.out.println("Generated Number: " + number);

processor.processNumber(number);

try {

Thread.sleep(1000); // Sleep for 1 second

} catch (InterruptedException e)

{ Thread.currentThread().interrupt();

}
}

class EvenNumberProcessor extends Thread {

private final NumberProcessor processor;

public EvenNumberProcessor(NumberProcessor processor) {

this.processor = processor;

public void run() {

while (true) {

Integer number = processor.getEvenNumber();

if (number != null) {

int square = number * number; System.out.println("Square

of " + number + ": " + square);

class OddNumberProcessor extends Thread {

private final NumberProcessor processor;

public OddNumberProcessor(NumberProcessor processor) {

this.processor = processor;

}
public void run() {

while (true) {

Integer number = processor.getOddNumber();

if (number != null) {

int cube = number * number * number;

System.out.println("Cube of " + number + ": " + cube);

class NumberProcessor {

private Integer evenNumber = null;

private Integer oddNumber = null;

public synchronized void processNumber(int number) {

if (number % 2 == 0) {

evenNumber = number;

notifyAll(); // Notify threads that a new even number is available

} else {

oddNumber = number;

notifyAll(); // Notify threads that a new odd number is available

}
public synchronized Integer getEvenNumber() {

while (evenNumber == null) {

try {

wait(); // Wait for an even number to be available

} catch (InterruptedException e)

{ Thread.currentThread().interrupt();

Integer number = evenNumber;

evenNumber = null; // Reset the even number

return number;

public synchronized Integer getOddNumber() {

while (oddNumber == null) {

try {

wait(); // Wait for an odd number to be available

} catch (InterruptedException e)

{ Thread.currentThread().interrupt();

Integer number = oddNumber;

oddNumber = null; // Reset the odd number

return number;

}
public class Main {

public static void main(String[] args) {

NumberProcessor processor = new NumberProcessor();

RandomNumberGenerator generator = new RandomNumberGenerator(processor);

EvenNumberProcessor evenProcessor = new EvenNumberProcessor(processor);

OddNumberProcessor oddProcessor = new OddNumberProcessor(processor);

generator.start();

evenProcessor.start();

oddProcessor.start();

2. import java.util.LinkedList;
import java.util.Queue;

class Producer extends Thread { private

final Queue<Integer> queue; private

final int maxSize;

public Producer(Queue<Integer> queue, int maxSize) {

this.queue = queue;

this.maxSize = maxSize;

public void run()

{ int value = 0;

while (true) {

synchronized (queue) {

while (queue.size() == maxSize) {

try {

queue.wait(); // Wait until space is available

} catch (InterruptedException e)

{ Thread.currentThread().interrupt();

System.out.println("Produced: " + value);

queue.add(value++);

queue.notify(); // Notify the consumer that a new item is available

}
}

class Consumer extends Thread {

private final Queue<Integer> queue;

public Consumer(Queue<Integer> queue) {

this.queue = queue;

public void run() {

while (true) {

synchronized (queue) {

while (queue.isEmpty()) {

try {

queue.wait(); // Wait until an item is available

} catch (InterruptedException e)

{ Thread.currentThread().interrupt();

int value = queue.poll();

System.out.println("Consumed: " + value);

queue.notify(); // Notify the producer that space is available

}
}

public class Main {

public static void main(String[] args)

{ Queue<Integer> queue = new LinkedList<>();

int maxSize = 5;

Producer producer = new Producer(queue, maxSize);

Consumer consumer = new Consumer(queue);

producer.start();

consumer.start();

}
3. class MyThread extends Thread {

public void run() {

System.out.println("Original Thread Name: " + Thread.currentThread().getName());

try {

Thread.sleep(5000); // Sleep for 5 seconds

} catch (InterruptedException e)

{ Thread.currentThread().interrupt();

} Thread.currentThread().setName("ChangedThreadName");

System.out.println("Changed Thread Name: " + Thread.currentThread().getName());

}
public class Main {

public static void main(String[] args)

{ MyThread thread = new

MyThread(); thread.start();

4. class CountdownThread extends Thread {

public void run() {

for (int i = 5; i >= 1; i--)

{ System.out.println("Count: " + i);

try {

Thread.sleep(6000); // Sleep for 6 seconds

} catch (InterruptedException e)

{ Thread.currentThread().interrupt();

} Thread.currentThread().setName("CountdownCompleteThread");

System.out.println("Changed Thread Name: " + Thread.currentThread().getName());

public class Main {


public static void main(String[] args) { CountdownThread

thread = new CountdownThread(); thread.start();

5. class UserThread extends Thread {

public void run() {

for (int i = 0; i < 5; i++)

{ System.out.println("User Thread: " + i);

try {

Thread.sleep(1000); // Sleep for 1 second

} catch (InterruptedException e)

{ Thread.currentThread().interrupt();

public class Main {

public static void main(String[] args)

{ UserThread userThread = new UserThread();


userThread.start(); // Start the user thread

for (int i = 0; i < 5; i++)

{ System.out.println("Main Thread: " + i);

try {

Thread.sleep(1000); // Sleep for 1 second

} catch (InterruptedException e)

{ Thread.currentThread().interrupt();

6. class Printer {

private final Object lock = new Object();

private int currentJob = 1;

public void printJob(int jobNumber) {

synchronized (lock) {

while (jobNumber != currentJob) {


try {

lock.wait(); // Wait for the correct job order

} catch (InterruptedException e)

{ Thread.currentThread().interrupt();

System.out.println("Printing Job: " + jobNumber);

currentJob++;

lock.notifyAll(); // Notify the next job

class JobThread extends Thread

{ private final Printer printer;

private final int jobNumber;

public JobThread(Printer printer, int jobNumber) {

this.printer = printer;

this.jobNumber = jobNumber;

public void run() {

printer.printJob(jobNumber);

}
public class Main {

public static void main(String[] args)

{ Printer printer = new Printer();

// Creating job threads in a non-sequential order

JobThread job1 = new JobThread(printer, 1);

JobThread job2 = new JobThread(printer, 2);

JobThread job3 = new JobThread(printer, 3);

JobThread job4 = new JobThread(printer, 4);

JobThread job5 = new JobThread(printer, 5);

job1.start();

job3.start();

job2.start();

job5.start();

job4.start();

7. class ThreadA extends Thread {


private final String str;

private int digitCount;

public ThreadA(String str) {

this.str = str;

public void run() {

for (char ch : str.toCharArray()) {

if (Character.isDigit(ch)) {

digitCount++;

System.out.println("ThreadA: " + digitCount);

class ThreadB extends Thread {

private final String str;

private int charCount;

public ThreadB(String str) {

this.str = str;

public void run() {


for (char ch : str.toCharArray()) {

if (Character.isAlphabetic(ch)) {

charCount++;

System.out.println("ThreadB: " + charCount);

public class Main {

public static void main(String[] args)

{ String k = "Hello123World456";

ThreadA threadA = new ThreadA(k);

ThreadB threadB = new ThreadB(k);

threadA.start();

threadB.start();

8. import java.util.Scanner;
class UserThreadPriority extends Thread {

private String k;

private char c;

public UserThreadPriority(String k, char c) {

this.k = k;

this.c = c;

public void run() {

System.out.println(getName() + ": String = " + k + ", Character = " + c);

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a string: ");

String inputString = scanner.nextLine();

System.out.print("Enter a character: ");

char inputChar = scanner.next().charAt(0);

UserThreadPriority threadobj1 = new UserThreadPriority(inputString, inputChar);

UserThreadPriority threadobj2 = new UserThreadPriority(inputString, inputChar);


threadobj1.setName("ThreadA");

threadobj2.setName("ThreadB");

threadobj1.start();

threadobj2.start();

scanner.close();

9. class SleepThread extends Thread {

private final long sleepTime;

public SleepThread(long sleepTime) {

this.sleepTime = sleepTime;

public void run() {

try {

System.out.println(getName() + " will sleep for " + sleepTime + " nanoseconds.");

Thread.sleep(sleepTime / 1_000_000); // Convert nanoseconds to milliseconds


System.out.println(getName() + " has woken up.");

} catch (InterruptedException e)

{ Thread.currentThread().interrupt();

public class Main {

public static void main(String[] args) { SleepThread

thread1 = new SleepThread(10); SleepThread

thread2 = new SleepThread(20); SleepThread

thread3 = new SleepThread(50); SleepThread

thread4 = new SleepThread(70); SleepThread

thread5 = new SleepThread(100);

thread1.start();

thread2.start();

thread3.start();

thread4.start();

thread5.start();

}
10. class PriorityThread extends Thread {

public PriorityThread(String name) {

super(name);

public void run() {

System.out.println(getName() + " with priority " + getPriority() + " is executing.");

public class Main {

public static void main(String[] args) {

PriorityThread thread1 = new PriorityThread("Thread 1");

PriorityThread thread2 = new PriorityThread("Thread 2");

PriorityThread thread3 = new PriorityThread("Thread 3");

PriorityThread thread4 = new PriorityThread("Thread 4");

PriorityThread thread5 = new PriorityThread("Thread 5");

// Set thread priorities


thread1.setPriority(Thread.MIN_PRIORITY); // 1

thread2.setPriority(Thread.NORM_PRIORITY); // 5

thread3.setPriority(Thread.MAX_PRIORITY); // 10

thread4.setPriority(Thread.MIN_PRIORITY); // 1

thread5.setPriority(Thread.NORM_PRIORITY); // 5

// Start threads

thread1.start();

thread2.start();

thread3.start();

thread4.start();

thread5.start();

You might also like