0% found this document useful (0 votes)
18 views20 pages

Java Concurrent Programming Examples

The document describes a Java program that implements multi-threading to generate random numbers and perform operations on those numbers using three threads. The first thread generates a random number every second, and if it is even the second thread computes the square and prints it, if odd the third thread computes the cube and prints it. Classes are defined for the random number generator thread and the calculation threads.
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)
18 views20 pages

Java Concurrent Programming Examples

The document describes a Java program that implements multi-threading to generate random numbers and perform operations on those numbers using three threads. The first thread generates a random number every second, and if it is even the second thread computes the square and prints it, if odd the third thread computes the cube and prints it. Classes are defined for the random number generator thread and the calculation threads.
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

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 [Link];

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");
[Link](); [Link](); [Link]();
}

class RandomNumberGenerator implements Runnable


{ @Override
public void run()

Random random = new Random();

while (true) { int randomNumber = [Link](100); // Generate a


random integer

between 0 and 99
[Link]([Link]().getName() + " generated: " +
randomNumber); if (randomNumber % 2 == 0) {

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

} else { new Thread(new


CubeCalculator(randomNumber)).start();

try {

[Link](1000); // Sleep for 1 second }


catch (InterruptedException e) {

[Link]();

class SquareCalculator implements Runnable


{ private int number;

public SquareCalculator(int number) {


[Link] = number;

@Override

public void run()

int square = number * number; [Link]("Square


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

}
class CubeCalculator implements Runnable
{ private int number;

public CubeCalculator(int number) {

[Link] = number;

@Override

public void run()

int cube = number * number * number;


[Link]("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 [Link];

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));

[Link]();

[Link]();

class Buffer {

private LinkedList<Integer> queue;

private int capacity;


public Buffer(int capacity) {

[Link] = capacity;

[Link] = new LinkedList<>();

public synchronized void produce(int item) throws InterruptedException


{ while ([Link]() == capacity) {
wait();

[Link](item);

[Link]("Produced: " + item);

notify();

public synchronized int consume() throws InterruptedException


{ while ([Link]()) {
wait();

int item = [Link]();

[Link]("Consumed: " + item);

notify(); return item;

class Producer implements Runnable {

private Buffer buffer;

public Producer(Buffer buffer) {

[Link] = buffer;

}
@Override

public void run()

try {

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

[Link](i);

[Link](1000); // Simulate production time

} catch (InterruptedException e) {

[Link]();

class Consumer implements Runnable {

private Buffer buffer;

public Consumer(Buffer buffer) {

[Link] = buffer;

@Override

public void run()

try {

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

int item = [Link]();

[Link](1000); // Simulate consumption time


}

} catch (InterruptedException e) {

[Link]();

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);

[Link]();

class MyRunnable implements Runnable {

@Override

public void run()

{ try {

[Link]("Thread is sleeping for 5 seconds.");


[Link](5000); // Sleep for 5 seconds

Thread currentThread = [Link]();

• Change the name of the thread


[Link]("MyNewThreadName");

[Link]("Thread name changed to: " + [Link]()); }


catch (InterruptedException e) {

[Link]();

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);

[Link]();

class MyRunnable implements Runnable {

@Override

public void run()

{ try {

Thread currentThread = [Link]();

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

[Link]("Thread " + [Link]() + " is sleeping for 6


seconds. Iteration: " + i);

[Link](6000); // Sleep for 6 seconds //

Change the name of the thread

[Link]("Thread-" + i);

} catch (InterruptedException e) {
[Link]();

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();


[Link]();

• Main thread sleeps for 1 second

try {

[Link](1000);

} catch (InterruptedException e) {

[Link]();

[Link]("Main thread completed.");


}

class UserDefinedThread extends Thread


{ @Override
public void run()

[Link]("User-defined thread started.");

• User-defined thread sleeps for 1 second


try {

[Link](1000);

} catch (InterruptedException e) {

[Link]();

[Link]("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 [Link];

import [Link];

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"));

[Link]();

[Link]();

[Link]();

class PrinterQueue {

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


private int currentJobNumber = 1;

public synchronized void print(String jobName) {

while (![Link]("Job " + currentJobNumber))


{ try { wait();

} catch (InterruptedException e) {

[Link]().interrupt();

[Link]("Printing: " + jobName);

currentJobNumber++;

notifyAll();

}
class PrintJob implements Runnable {

private PrinterQueue printerQueue;

private String jobName;

public PrintJob(PrinterQueue printerQueue, String jobName)


{ [Link] = printerQueue;
[Link] = jobName;

@Override

public void run()


{

[Link](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);
[Link]();

• Create ThreadB to count alphabetic characters


ThreadB threadB = new ThreadB(k);
[Link]();
}

class ThreadA extends Thread {

private String input;

public ThreadA(String input) {

[Link] = input;

@Override

public void run()

int digitsCount = 0; for (char ch :

[Link]()) { if

([Link](ch)) {

digitsCount++;

[Link]("ThreadA:" + digitsCount);

class ThreadB extends Thread {


private String input;

public ThreadB(String input) {

[Link] = input;

@Override

public void run()

int alphabeticCount = 0; for (char

ch : [Link]()) { if

([Link](ch)) {

alphabeticCount++;

[Link]("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 [Link];
public class UserThreadPriority extends Thread
{ private String k; private char c;

public UserThreadPriority(String name) {

super(name);

@Override

public void run()

[Link]("Thread " + getName() + " is running.");


[Link]("k: " + k);

[Link]("c: " + c);

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

[Link]("Enter a String (k): "); String


userInputString = [Link]();

[Link]("Enter a Character (c): "); char


userInputChar = [Link]().charAt(0);
[Link]();

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
[Link]();
[Link]();

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);

[Link]();

[Link]();

[Link]();

[Link]();

[Link]();

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;
[Link] = sleepDuration;

@Override

public void run()

[Link](getName() + " is running.");

[Link]("k: " + k);

[Link]("c: " + c);

try {

[Link](sleepDuration); // Sleep for the specified nanoseconds

} catch (InterruptedException e)
{ [Link]();

[Link](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);


[Link](); [Link](); [Link](); [Link](); [Link]();

}
class CustomThread extends Thread {

public CustomThread(String name, int priority)


{ super(name);
setPriority(priority);

@Override

public void run()

[Link](getName() + " is running with priority " + getPriority());

OUTPUT :

Common questions

Powered by AI

Controlling thread execution with the sleep method pauses a thread temporarily, effectively simulating delays or timed waiting within a thread's logic. This approach is straightforward but lacks precision in coordinating thread interaction and can lead to resource idling. Synchronization, on the other hand, precisely manages thread access to shared resources, preventing race conditions and ensuring orderly execution. Synchronization is advantageous for managing complex interactions reliably, but it increases overhead and potential for deadlocks if not managed correctly. Sleep is simpler but less effective for intricate scheduling needs .

Java's concurrency model handles exceptions within threads by allowing each thread to manage its own exceptions through try-catch blocks encapsulating its run() logic, as demonstrated in handling InterruptedException in the examples. Uncaught exceptions within a thread cause its abrupt termination without affecting the parent thread's execution or other threads unless specifically propagated. The potential implication of this model is that unhandled exceptions can result in incomplete operations or data corruption, highlighting the importance of robust error handling and recovery strategies within concurrent code .

The implementation distinguishes digit from alphabet counting by assigning each task to separate threads, ThreadA and ThreadB, which independently traverse the string character array. ThreadA counts digits using Character.isDigit(), while ThreadB counts alphabetic characters using Character.isLetter(). This separation is effective as it divides the processing task, allowing parallel execution and potentially reducing time complexity for larger strings. However, the overall program efficiency might not significantly improve due to the light computational load per character when counting .

The use of Thread.sleep() in Java pauses the execution of a thread temporarily without consuming CPU resources, which can be beneficial for reducing CPU load and managing timing in concurrent applications. However, excessive use or improper placement of sleep intervals can negatively impact the application's performance and reliability by introducing unnecessary delays. For instance, in the ThreadNameChangeReverseOrder example, each loop iteration includes a 6-second sleep. Such long sleeps could delay responsiveness and completion of important tasks, although it can be useful for simulating prolonged operations without complex synchronization .

Thread synchronization in the printer synchronization program ensures that print jobs are executed in a specific order using synchronized methods and wait/notify mechanisms. The PrinterQueue class synchronizes the print method, which uses a counter to track the current job number. If a job name does not match the expected current job, the thread waits. When the correct job is reached, it prints and increments the current job number, notifying all waiting threads to check again. This guarantees that jobs print sequentially in their intended order .

Changing a thread's name during its execution has no impact on its functionality or performance; it mainly serves to enhance readability and debugging. In the examples, after a thread sleeps for a defined period, its name is changed within its runnable implementation to indicate progression or the current stage of operation. This is demonstrated by renaming threads in both the ThreadNameChangeExample and ThreadNameChangeReverseOrder programs using the setName() method after the sleep period .

The Java program solves the producer-consumer problem by using a synchronized Buffer class to manage shared resource access. The program creates a buffer (a linked list with a specified capacity) where the producer thread adds items, and the consumer thread removes them. Synchronization is implemented through the use of wait() and notify() methods to control the actions when the buffer is full or empty. The produce(int item) method ensures an item is only added when the buffer is not at capacity, and the consume() method ensures an item is only removed when the buffer is not empty .

The program demonstrates thread priority by creating five threads, each with a specified priority level (MIN_PRIORITY, NORM_PRIORITY, MAX_PRIORITY). The CustomThread class sets thread priority in its constructor. Although thread priority can influence the order of execution, the JVM's handling of it may not guarantee strict adherence to priority levels across different platforms. As a result, the observed execution order may not always reflect the expected priority to completion sequence but is used to allow potentially faster scheduling of higher-priority threads .

The Runnable interface implementation involves defining the run() method within a separate class, which is instantiated by passing it to a Thread object. Conversely, extending the Thread class involves subclassing Thread and overriding its run() method. The significance of using Runnable is its flexibility, enabling a class to execute alongside extending another class, promoting better design through composition. Extending Thread is simpler but limits class inheritance. Runnable is generally preferred for larger applications for its modularity, facilitating decoupled and maintainable code .

In the multi-thread application, the first thread generates a random integer every second. If the generated integer is even, the second thread calculates its square and prints the result. If the integer is odd, the third thread calculates its cube and prints it. These operations are handled by instantiating separate threads of SquareCalculator or CubeCalculator based on the parity of the generated number .

You might also like