Saturday 29 April 2023

Extend the thread to check it’s running status

Extend thread class to support following functionalities.

 

boolean isFinished()

Return true then thread finishes its execution, else false.

 

public void waitUntilFinished(long timeout)

Wait until the thread finished it’s execution or the timeout is elapsed.

 

Find the below working application.

 


WorkerThread.java

package com.sample.app.threads;

public class WorkerThread extends Thread {
	private Object notify;
	private volatile boolean finished = false;
	private final Runnable runnable;

	public WorkerThread(Runnable runnable, Object notify) {
		this.runnable = runnable;
		this.notify = notify != null ? notify : this;
	}

	public WorkerThread(Runnable runnable) {
		this(runnable, null);
	}

	public synchronized boolean isFinished() {
		return finished;
	}

	public void waitUntilFinished(long timeout) throws InterruptedException {
		long endTime = System.currentTimeMillis() + timeout;
		synchronized (notify) {
			long currentTime = System.currentTimeMillis();
			while (!finished && currentTime < endTime) {
				notify.wait(endTime - currentTime);
				currentTime = System.currentTimeMillis();
			}
		}
	}

	public void run() {
		try {
			runnable.run();
		} catch (Throwable t) {
			t.printStackTrace(System.err);
			throw t;
		} finally {
			synchronized (notify) {
				finished = true;
				notify.notifyAll();
			}
		}
	}
}

 

WorkerThreadDemo.java

package com.sample.app.threads;

import java.util.concurrent.TimeUnit;

public class WorkerThreadDemo {

	public static void main(String[] args) throws InterruptedException {
		Runnable runnable = new Runnable() {

			@Override
			public void run() {
				System.out.println("Started executing the process");
				try {
					TimeUnit.SECONDS.sleep(6);
				} catch (InterruptedException e) {
					e.printStackTrace(System.err);
				}
				System.out.println("Finished execution....");
			}
		};

		WorkerThread workerThread = new WorkerThread(runnable);

		workerThread.start();

		workerThread.waitUntilFinished(4000l);
		System.out.println("Is finished : " + workerThread.isFinished());

		workerThread.waitUntilFinished(3000l);
		System.out.println("Is finished : " + workerThread.isFinished());

	}

}

 

Output

Started executing the process
Is finished : false
Finished execution....
Is finished : true

 

 

 

You may like

Interview Questions

Quick guide to assertions in Java

java.util.Date vs java.sql.Date

How to break out of nested loops in Java?

Implementation of Bag data structure in Java

Scanner throws java.util.NoSuchElementException while reading the input

How to get all the enum values in Java?

No comments:

Post a Comment