You are on page 1of 20

NAME – S.

Abhisesha Kumaara
REG NO - RA2211026010487

21CSC203P - ADVANCED PROGRAMMING


PRACTICE WEEK - 7

CONCURRENT PROGRAMMING PARADIGM: THREAD


CLASSES AND METHODS

1. Write a java program that implements a multi-thread application that


has three threads. First thread generates a random integer every 1 second
and if the value is even, the second thread computes the square of the
number and prints. If the value is odd, the third thread will print the value
of the cube of the number.

import java.util.Random;

public class MultiThreadExample {

public static void main(String[] args) {

RandomNumberGenerator generator = new RandomNumberGenerator();


Thread thread1 = new Thread(generator, "Thread 1");

Thread thread2 = new Thread(generator, "Thread 2");


Thread thread3 = new Thread(generator, "Thread 3");
thread1.start(); thread2.start(); thread3.start();
}

class RandomNumberGenerator implements Runnable


{ @Override
public void run()

Random random = new Random();

while (true) { int randomNumber = random.nextInt(100); // Generate a


random integer

between 0 and 99
System.out.println(Thread.currentThread().getName() + " generated: " +
randomNumber); if (randomNumber % 2 == 0) {

new Thread(new SquareCalculator(randomNumber)).start();

} else { new Thread(new


CubeCalculator(randomNumber)).start();

try {

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


catch (InterruptedException e) {

e.printStackTrace();

class SquareCalculator implements Runnable


{ private int number;

public SquareCalculator(int number) {


this.number = number;

@Override

public void run()

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


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

}
class CubeCalculator implements Runnable
{ private int number;

public CubeCalculator(int number) {

this.number = number;

@Override

public void run()

int cube = number * number * number;


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

OUTPUT :
1. Write a java program for to solve producer consumer problem in
which a producer produce a value and consumer consume the value
before producer generate the next value.

import java.util.LinkedList;

public class ProducerConsumer {

public static void main(String[] args)

Buffer buffer = new Buffer(5);

Thread producerThread = new Thread(new Producer(buffer)); Thread


consumerThread = new Thread(new Consumer(buffer));

producerThread.start();

consumerThread.start();

class Buffer {

private LinkedList<Integer> queue;

private int capacity;


public Buffer(int capacity) {

this.capacity = capacity;

this.queue = new LinkedList<>();

public synchronized void produce(int item) throws InterruptedException


{ while (queue.size() == capacity) {
wait();

queue.add(item);

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

notify();

public synchronized int consume() throws InterruptedException


{ while (queue.isEmpty()) {
wait();

int item = queue.removeFirst();

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

notify(); return item;

class Producer implements Runnable {

private Buffer buffer;

public Producer(Buffer buffer) {

this.buffer = buffer;

}
@Override

public void run()

try {

for (int i = 1; i <= 10; i++) {

buffer.produce(i);

Thread.sleep(1000); // Simulate production time

} catch (InterruptedException e) {

e.printStackTrace();

class Consumer implements Runnable {

private Buffer buffer;

public Consumer(Buffer buffer) {

this.buffer = buffer;

@Override

public void run()

try {

for (int i = 1; i <= 10; i++) {

int item = buffer.consume();

Thread.sleep(1000); // Simulate consumption time


}

} catch (InterruptedException e) {

e.printStackTrace();

OUTPUT :
1. Write a java program in which threads sleep for 5 sec and change the
name of the thread.

public class ThreadNameChangeExample


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

Runnable threadRunnable = new MyRunnable();


Thread thread = new Thread(threadRunnable);

thread.start();

class MyRunnable implements Runnable {

@Override

public void run()

{ try {

System.out.println("Thread is sleeping for 5 seconds.");


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

Thread currentThread = Thread.currentThread();

• Change the name of the thread


currentThread.setName("MyNewThreadName");

System.out.println("Thread name changed to: " + currentThread.getName()); }


catch (InterruptedException e) {

e.printStackTrace();

OUTPUT :
1. Write a java program in which threads sleep for 6 sec in the loop in
reverse order from 5 to 1 and change the name of the thread.

public class ThreadNameChangeReverseOrder


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

Runnable threadRunnable = new MyRunnable();


Thread thread = new Thread(threadRunnable);

thread.start();

class MyRunnable implements Runnable {

@Override

public void run()

{ try {

Thread currentThread = Thread.currentThread();

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

System.out.println("Thread " + currentThread.getName() + " is sleeping for 6


seconds. Iteration: " + i);

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

Change the name of the thread

currentThread.setName("Thread-" + i);

} catch (InterruptedException e) {
e.printStackTrace();

OUTPUT :

1. Write a java program for multi thread in which user thread and thread
started from the main method invoked at a time each thread sleeps for 1
sec.

public class MultiThreadExample {

public static void main(String[] args) {

• Create and start the user-defined thread

UserDefinedThread userThread = new UserDefinedThread();


userThread.start();

• Main thread sleeps for 1 second

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

System.out.println("Main thread completed.");


}

class UserDefinedThread extends Thread


{ @Override
public void run()

System.out.println("User-defined thread started.");

• User-defined thread sleeps for 1 second


try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

System.out.println("User-defined thread completed.");

OUTPUT :

1. Write a java program to solve printer synchronisation problems in


which all the jobs must be completed in order.

import java.util.Queue;

import java.util.LinkedList;

public class PrinterSynchronization {


public static void main(String[] args) {

PrinterQueue printerQueue = new PrinterQueue();

Thread job1 = new Thread(new PrintJob(printerQueue, "Job 1"));

Thread job2 = new Thread(new PrintJob(printerQueue, "Job 2"));

Thread job3 = new Thread(new PrintJob(printerQueue, "Job 3"));

job1.start();

job2.start();

job3.start();

class PrinterQueue {

private Queue<String> queue = new LinkedList<>();


private int currentJobNumber = 1;

public synchronized void print(String jobName) {

while (!jobName.equals("Job " + currentJobNumber))


{ try { wait();

} catch (InterruptedException e) {

Thread.currentThread().interrupt();

System.out.println("Printing: " + jobName);

currentJobNumber++;

notifyAll();

}
class PrintJob implements Runnable {

private PrinterQueue printerQueue;

private String jobName;

public PrintJob(PrinterQueue printerQueue, String jobName)


{ this.printerQueue = printerQueue;
this.jobName = jobName;

@Override

public void run()


{

printerQueue.print(jobName);

OUTPUT :

7. Create a java program for the following


Use ThreadA to find number of digits present in the string k and store
into variable dc, finally print the value of dc(output format:
ThreadA:digitscount).

Use ThreadB to find number of alphabetic present in the string k and


store into variable cc, finally print the value of cc(output
format:ThreadB:digitscount).

public class CountCharactersInString {

public static void main(String[] args) {


String k = "Hello123World456";

• Create ThreadA to count digits


ThreadA threadA = new ThreadA(k);
threadA.start();

• Create ThreadB to count alphabetic characters


ThreadB threadB = new ThreadB(k);
threadB.start();
}

class ThreadA extends Thread {

private String input;

public ThreadA(String input) {

this.input = input;

@Override

public void run()

int digitsCount = 0; for (char ch :

input.toCharArray()) { if

(Character.isDigit(ch)) {

digitsCount++;

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

class ThreadB extends Thread {


private String input;

public ThreadB(String input) {

this.input = input;

@Override

public void run()

int alphabeticCount = 0; for (char

ch : input.toCharArray()) { if

(Character.isLetter(ch)) {

alphabeticCount++;

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

OUTPUT :

1. Create two objects threadobj1 and threadobj2 for the class


UserThreadPriority. Set the name of threadobj1 as “ThreadA” and
threadobj2 as “ThreadB”. Get a String and a Character from the user and
assign into UserThreadPriority class variable k and c respectively. Call the
start() method for the thread objects threadobj1 and threadobj2.

import java.util.Scanner;
public class UserThreadPriority extends Thread
{ private String k; private char c;

public UserThreadPriority(String name) {

super(name);

@Override

public void run()

System.out.println("Thread " + getName() + " is running.");


System.out.println("k: " + k);

System.out.println("c: " + c);

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a String (k): "); String


userInputString = scanner.nextLine();

System.out.print("Enter a Character (c): "); char


userInputChar = scanner.next().charAt(0);
scanner.close();

UserThreadPriority threadobj1 = new UserThreadPriority("ThreadA");


UserThreadPriority threadobj2 = new UserThreadPriority("ThreadB");

• Assign user inputs to thread variables


threadobj1.k = userInputString;
threadobj1.c = userInputChar;

threadobj2.k = userInputString;

threadobj2.c = userInputChar;
• Start the threads
threadobj1.start();
threadobj2.start();

OUTPUT :

1. Write java program using sleep() method of Thread class where the
new class thread created from the previous class is implemented by
using sleep method for 10,20,50,70,100 ns

public class SleepDemo { public static

void main(String[] args) { String k =

"Hello, World!"; char c = 'X';

UserThreadPriority threadobj1 = new UserThreadPriority("ThreadA", k, c, 10);

UserThreadPriority threadobj2 = new UserThreadPriority("ThreadB", k, c, 20);

UserThreadPriority threadobj3 = new UserThreadPriority("ThreadC", k, c, 50);

UserThreadPriority threadobj4 = new UserThreadPriority("ThreadD", k, c, 70);

UserThreadPriority threadobj5 = new UserThreadPriority("ThreadE", k, c, 100);

threadobj1.start();

threadobj2.start();

threadobj3.start();

threadobj4.start();

threadobj5.start();

class UserThreadPriority extends Thread {


private String k; private char c; private

long sleepDuration;

public UserThreadPriority(String name, String k, char c, long sleepDuration)


{ super(name); this.k = k; this.c = c;
this.sleepDuration = sleepDuration;

@Override

public void run()

System.out.println(getName() + " is running.");

System.out.println("k: " + k);

System.out.println("c: " + c);

try {

Thread.sleep(sleepDuration); // Sleep for the specified nanoseconds

} catch (InterruptedException e)
{ e.printStackTrace();

System.out.println(getName() + " has finished after sleeping for " +


sleepDuration + " nanoseconds.");

OUTPUT :
1. Write a java Thread program using Thread Priority for 5 processes
and execute the priority order among the processes.

public class ThreadPriorityExample {


public static void main(String[] args) {

Thread thread1 = new CustomThread("Thread 1", Thread.MIN_PRIORITY); Thread


thread2 = new CustomThread("Thread 2", Thread.NORM_PRIORITY); Thread
thread3 = new CustomThread("Thread 3", Thread.NORM_PRIORITY); Thread
thread4 = new CustomThread("Thread 4", Thread.MAX_PRIORITY);

Thread thread5 = new CustomThread("Thread 5", Thread.MAX_PRIORITY);


thread1.start(); thread2.start(); thread3.start(); thread4.start(); thread5.start();

}
class CustomThread extends Thread {

public CustomThread(String name, int priority)


{ super(name);
setPriority(priority);

@Override

public void run()

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

OUTPUT :

You might also like