Java Thread State

You might also like

You are on page 1of 1

Getting the execution progress percentage of a thread is not a straightforward task in Java,

as it depends on the nature of the thread's work. Generally, you'll need to implement some
form of tracking mechanism within the thread's code to calculate the progress.
Here's a basic outline of how you can achieve this:
Define a variable to track the progress in your thread class.
As the thread executes its work, update the progress variable based on the progress of the
task.
Calculate the percentage using the total work and the progress made.
Let's illustrate this with a simple example. Suppose we have a custom MyThread class that
performs some computation, and we want to track its execution progress:
javaCopy code
public class MyThread extends Thread {
private int progress; private int totalWork; public MyThread(int totalWork) { this .progress = 0 ;
this .totalWork = totalWork; } @Override public void run() { for ( int i = 0 ; i < totalWork; i++) { //
Simulating some work being done // Replace this with your actual computation doSomeWork(); // Update
progress progress = (i * 100 ) / totalWork; } } private void doSomeWork() { // Simulating work being done
(replace this with your actual computation) try { Thread.sleep( 100 ); // Simulate some delay } catch
(InterruptedException e) { e.printStackTrace(); } } public int getProgress() { return progress; } }
In this example, the MyThread class takes totalWork as an argument, and in the run()
method, it performs the computation in a loop. After each iteration, it updates the progress
variable based on the percentage of work completed.
You can then use the getProgress() method to get the progress percentage of the thread's
execution at any point:
javaCopy code
MyThread myThread = new MyThread ( 100 ); // Total work = 100 myThread.start(); while
(myThread.isAlive()) { System.out.println( "Progress: " + myThread.getProgress() + "%" ); try
{ Thread.sleep( 500 ); // Just to avoid excessive output, you can adjust this } catch (InterruptedException e)
{ e.printStackTrace(); } } System.out.println( "Thread execution completed!" );
Remember that this is a simple example, and in real-world scenarios, you'll need to adapt
the progress tracking mechanism according to the actual task being performed by the
thread. Additionally, thread safety should be taken into consideration if multiple threads are
involved in updating progress.

You might also like