0% found this document useful (0 votes)
16 views12 pages

Skill Week 8

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

Skill Week 8

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

SKILL WEEK-8

T.Jithendra krishna
2300033073
1) Thread Life Cycle Monitoring

Implement a Java program where you create and start multiple threads, each of which
simulates different stages of a thread's life cycle (e.g., NEW, RUNNABLE,
BLOCKED, WAITING, TERMINATED). The program should print a log of each
thread's state transitions. Use appropriate thread synchronization techniques to
simulate the BLOCKED and WAITING states.

Expected Output:

The output should provide a detailed log of each thread’s state transitions, indicating
when each state change occurs. For example:

Thread 1: NEW
Thread 1: RUNNABLE
Thread 1: BLOCKED (waiting for Thread 2) Thread 2: NEW
Thread 2: RUNNABLE
Thread 2: enters synchronized block
Thread 1: RUNNABLE
Thread 1: WAITING (waiting for notification) Thread 2: sends notification
Thread 1: RUNNABLE
Thread 1: TERMINATED
Thread 2: exits synchronized block Thread
2: TERMINATED

CODE:

package klu; class ThreadLifeCycle extends Thread {

private final Object lock; private final String

threadName; public ThreadLifeCycle(String name,

Object lock) { this.threadName = name;

this.lock = lock;

System.out.println(threadName + ": NEW");

@Override
public void run() {

try {

System.out.println(threadName + ": RUNNABLE");

synchronized (lock) {

System.out.println(threadName + ": enters synchronized block");

Thread.sleep(1000); lock.wait();

System.out.println(threadName + ": WAITING (waiting for notification)");

System.out.println(threadName + ": RUNNABLE");

} catch (InterruptedException e) {

e.printStackTrace();

} finally {

System.out.println(threadName + ": TERMINATED");

class ThreadLifeCycleMonitor {

public static void main(String[] args) {

final Object lock = new Object();

ThreadLifeCycle thread1 = new ThreadLifeCycle("Thread 1", lock);


ThreadLifeCycle thread2 = new ThreadLifeCycle("Thread 2", lock);

thread1.start();

try {
Thread.sleep(500);

} catch (InterruptedException e) {

e.printStackTrace();

new Thread(() -> {

System.out.println("Thread 2: NEW");

System.out.println("Thread 2: RUNNABLE"); synchronized

(lock) {

System.out.println("Thread 2: enters synchronized block");

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

System.out.println("Thread 2: sends notification");

lock.notify();

System.out.println("Thread 2: exits synchronized block");

System.out.println("Thread 2: TERMINATED");

}).start(); try

thread1.join();
} catch (InterruptedException e) {

e.printStackTrace();

OUTPUT:

2).Thread Pools for Efficient Task Execution

You are working on a web server that handles multiple client requests concurrently. Instead of
creating a new thread for every request, you want to manage the threads efficiently using a
thread pool.

Implementation Steps:

1. Define the Request Processing Task:

o Create a class that implements the Runnable interface to simulate request processing. Each
instance of this class will represent a single client request.

2. Create the Thread Pool:


o Utilize Executors.newFixedThreadPool(int nThreads) to create a thread pool with a fixed
number of threads. This will control the maximum number of concurrent requests being
processed.

3. Submit Tasks to the Thread Pool:

o In the main method, simulate incoming requests by creating instances of the request
processing task and submitting them to the thread pool for execution.

4. Shutdown the Thread Pool:

o Use the shutdown() method on the ExecutorService instance to initiate an orderly shutdown,
allowing previously submitted tasks to execute before terminating the pool.

CODE:

package klu; import

java.util.concurrent.ExecutorService; import

java.util.concurrent.Executors; import

java.util.concurrent.TimeUnit; class

ClientRequest implements Runnable {

private final String requestName; public

ClientRequest(String requestName) {

this.requestName = requestName;

@Override

public void run() {

System.out.println(Thread.currentThread().getName() + " is processing " +


requestName);

try {

Thread.sleep(2000);

} catch (InterruptedException e) {

e.printStackTrace();

}
System.out.println(Thread.currentThread().getName() + " has completed " +
requestName);

} class WebServerSimulation { public

static void main(String[] args) { int

poolSize = 5;

ExecutorService threadPool = Executors.newFixedThreadPool(poolSize);

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

ClientRequest request = new ClientRequest("Request " + i);

threadPool.submit(request);

threadPool.shutdown();

try {

if (!threadPool.awaitTermination(60, TimeUnit.SECONDS)) {

threadPool.shutdownNow();

} catch (InterruptedException e) {

threadPool.shutdownNow();

OUTPUT:
3). You are developing a task scheduling system where tasks are assigned different priorities. Use a
Priority Queue to store tasks based on their priority and assign threads from a thread pool to process
the highest-priority tasks first. Ensure that lower-priority tasks are still processed, but only after higher-
priority tasks have been completed.

Key Components:

1. Task Class: Each task has a priority and a name or some other identifier.
2. Priority Queue: A PriorityQueue is used to store the tasks, where tasks with the highest priority
are processed first (lower number indicates higher priority).
3. Thread Pool: A ThreadPoolExecutor is used to manage a pool of worker threads that will
execute the tasks concurrently.
4. Task Submission: Tasks are submitted to the priority queue and processed by threads in priority
order.

CODE:

package klu; import java.util.PriorityQueue;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.TimeUnit;

class Task implements Comparable<Task>, Runnable {


private final int priority; private final

String taskName; public Task(int priority,

String taskName) { this.priority =

priority; this.taskName = taskName;

@Override public int compareTo(Task other) {

return Integer.compare(this.priority, other.priority);

@Override

public void run() {

System.out.println(Thread.currentThread().getName() + " is processing " + taskName + " with


priority " + priority);

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

System.out.println(Thread.currentThread().getName() + " has completed " + taskName + " with


priority " + priority);

public int getPriority() {

return priority;

}
public String getTaskName() {

return taskName;

class TaskScheduler { private final

PriorityQueue<Task> taskQueue; private final

ExecutorService threadPool;

public TaskScheduler(int poolSize) { taskQueue = new

PriorityQueue<>(); threadPool =

Executors.newFixedThreadPool(poolSize);

public synchronized void submitTask(Task task) {

taskQueue.offer(task);

notify();

public void startProcessing() { while

(!Thread.currentThread().isInterrupted()) {

Task task; synchronized

(this) { while

(taskQueue.isEmpty()) {

try {

wait();

} catch (InterruptedException e) {

Thread.currentThread().interrupt();
}

task = taskQueue.poll();

threadPool.execute(task); }

public void shutdownScheduler() {

threadPool.shutdown();

try {

if (!threadPool.awaitTermination(60, TimeUnit.SECONDS)) {

threadPool.shutdownNow();

} catch (InterruptedException e) {

threadPool.shutdownNow();

class PriorityTaskSchedulerDemo {

public static void main(String[] args) {

TaskScheduler scheduler = new TaskScheduler(3);

scheduler.submitTask(new Task(3, "Task 1"));

scheduler.submitTask(new Task(1, "Task 2"));

scheduler.submitTask(new Task(2, "Task 3"));

scheduler.submitTask(new Task(1, "Task 4"));


scheduler.submitTask(new Task(5, "Task 5")); new

Thread(scheduler::startProcessing).start();

try {

Thread.sleep(3000); } catch

(InterruptedException e) {

e.printStackTrace();

scheduler.submitTask(new Task(4, "Task 6"));

try {

Thread.sleep(8000); }

catch (InterruptedException e) {

e.printStackTrace();

scheduler.shutdownScheduler();

OUTPUT:

You might also like