I am new to multi threading and while practising I wrote the following code. I want to call the createThred method to create a new thread evrytime I call it. However, With the below given code, everytime the createThread method is called, i get the same thread running again and again. Is it possible to create a new thread using the same object? Appararently not but just wanted to confirm if there is a way I dont know of.
public class ThreadStartRunnable implements Runnable {
private Thread t;
/*
ThreadStartRunnable(String name) {
t = new Thread(this, name);
t.start();
}
*/
private Thread createThread(String name){
t = new Thread(this,name);
t.start();
return t;
}
/**
* @Override run
*
*/
public void run() {
for(int i=0;i<=5;i++)
{
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("The current Thread is " + t.getName() + " and thread ID is " + t.getId());
}
}
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t = Thread.currentThread();
//new ThreadStartRunnable("User 1");
//new ThreadStartRunnable("User 2");
//ThreadStartRunnable c = new ThreadStartRunnable();
ThreadStartRunnable t1 = new ThreadStartRunnable();
t1.createThread("Child 1");
t1.createThread("Child 2");
for(int i=0;i<=5;i++)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("The cirrent Thread is " + t.getName()+ " and thread ID is " + t.getId());
}
}
}
OUTPUT:
The current Thread is Child 2 and thread ID is 9
The current Thread is Child 2 and thread ID is 9
The cirrent Thread is main and thread ID is 1
The current Thread is Child 2 and thread ID is 9
The current Thread is Child 2 and thread ID is 9
The current Thread is Child 2 and thread ID is 9
The current Thread is Child 2 and thread ID is 9
The current Thread is Child 2 and thread ID is 9
The current Thread is Child 2 and thread ID is 9
The cirrent Thread is main and thread ID is 1
The current Thread is Child 2 and thread ID is 9
The current Thread is Child 2 and thread ID is 9
The current Thread is Child 2 and thread ID is 9
The current Thread is Child 2 and thread ID is 9
The cirrent Thread is main and thread ID is 1
The cirrent Thread is main and thread ID is 1
The cirrent Thread is main and thread ID is 1
The cirrent Thread is main and thread ID is 1