Java Multi Threaded – Execution time

Previous
Next

Execution time of Multi threaded application:

  • When we execute different logics from different threads, time consumption will decrease.
  • Multi threaded application increase the stress on processor by utilizing efficiently.
class PrintNumbers
{
	static void print1to50()
	{
		for (int i=1 ; i<=50 ; i++)
		{
			System.out.println("i value : " + i);
			try{
				Thread.sleep(100);
			}catch(Exception e){ }
		}
	}
	static void print50to1()
	{
		for (int j=50 ; j>=1 ; j--)
		{
			System.out.println("j value : " + j);
			try{
				Thread.sleep(100);
			}catch(Exception e){ }
		}
	}
}
class Custom1 extends Thread
{
	public void run()
	{
		PrintNumbers.print1to50();
	}
}
class Custom2 extends Thread
{
	public void run()
	{
		PrintNumbers.print50to1();
	}
}
class ExecutionTime 
{
	public static void main(String[] args) throws Exception
	{
		Custom1 t1 = new Custom1();
		Custom2 t2 = new Custom2();

		long s = System.currentTimeMillis();
		t1.start();
		t2.start();

		t1.join();
		t2.join();
		long e = System.currentTimeMillis();

		System.out.println("Time taken : " + (e-s)/1000 + " Seconds");
	}
}
Previous
Next

Add Comment

Courses Enquiry Form