dcsimg
 

Running Multiple Instances of a Thread in Java

Monday May 24th 2021 by MS Sridhar
Article Image

Is it possible to run more than one instance of a thread in Java? We answer this question in today’s article. Find out now.

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)
Home
Mobile Site | Full Site