Multiple Custom Threads in Java

Previous
Next

How can we execute different logics from different threads?

  • We can create multiple thread objects for a single thread class.
  • We can define only run() method in thread class.
  • When we start multiple threads of same class, it executes run() logic from each thread.
class Custom1 extends Thread
{
	public void run() 
	{
		for (int i=1 ; i<=10 ; i++)
		{
			System.out.println("Custom1 logic : " + i);
			try{
				Thread.sleep(1000);
			}catch(InterruptedException e){  }
		}
	}
}
class Custom2 extends Thread
{
	public void run() 
	{
		for (int i=60 ; i<=80 ; i++)
		{
			System.out.println("Custom2 logic : " + i);
			try{
				Thread.sleep(1000);
			}catch(InterruptedException e){  }
		}
	}
}
class Custom3 extends Thread
{
	public void run() 
	{
		for (int i=100 ; i<=150 ; i++)
		{
			System.out.println("Custom3 logic : " + i);
			try{
				Thread.sleep(1000);
			}catch(InterruptedException e){  }
		}
	}
}
class Default 
{
	public static void main(String[] args) 
	{
		Custom1 c1 = new Custom1();
		c1.start();

		Custom2 c2 = new Custom2();
		c2.start();

		Custom3 c3 = new Custom3();
		c3.start();
	}
}
Previous
Next

Add Comment

Courses Enquiry Form