dcsimg
LinkedIn
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
May 24, 2021

Running Multiple Instances of a Thread in Java

You may have heard that you can run more than one instance of a thread in Java, however - as the code example below illustrates - this is not possible. Try out the following code snippet to see what happens when you attempt this:

*/

public class ThreadInstance extends Thread{  

    public static void main(String[] args) throws InterruptedException
	{
		ThreadInstance threadInstance = new ThreadInstance();
		threadInstance.start();
		threadInstance.sleep(1);
		threadInstance.start();
	}

	public void run(){  
		System.out.println("In run method.");  
	}  
}

/*

:Output:

$java ThreadInstance
In run method.
Exception in thread "main" java.lang.IllegalThreadStateException
        at java.lang.Thread.start(Unknown Source)
        at ThreadInstance.main(ThreadInstance.java:10)
MS Sridhar
 
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date