Creating Threads : New thread doesn't run( )
Hello !
Can anyone please check the error in this code. It does not start the new thread.
God bless you.
NADEEM.
// Create a second thread
class NewThreadimplements Runnable{
Thread t ;
NewThread(){
try{
t =new Thread(this.t ,"New Thread");// Create a new, second thread.
System.out.println("Child Thread : " + t);
t.start();// start the thread.
}catch (IllegalThreadStateException e){
System.out.println("Exception : " + e);
}
}
//Entry point for the second thread.
publicvoid run(){
try{
for(int i = 5; i > 0; i--){
System.out.println("Child Thread : " + i);
Thread.sleep(500);
}
}catch (InterruptedException e){
System.out.println("Child Thread interrupted ");
}
System.out.println("Exiting Child Thread... ");
}
}
class CreatingThread{
publicstaticvoid main(String args[]){
new NewThread();// Create a new Thread
try{
for(int i = 5; i > 0; i--){
System.out.println("Main Thread : " + i);
Thread.sleep(1000);
}
}catch (InterruptedException e){
System.out.println("Main Thread interrupted ");
}
System.out.println("Exiting main thread ");
}
}
are you sure Nadeem...i compiled and ran the below code and it works as you designed it...what errors do u get when u try to compile?...
class NewThread implements Runnable {
Thread t ;
NewThread() {
try {
t = new Thread(this , "New Thread");// Create a new, second thread.
System.out.println("Child Thread : " + t);
t.start();// start the thread.
}catch (IllegalThreadStateException e) {
System.out.println("Exception : " + e);
}
}
//Entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread : " + i);
Thread.sleep(500);
}
}catch (InterruptedException e) {
System.out.println("Child Thread interrupted ");
}
System.out.println("Exiting Child Thread... ");
}
}
class CreatingThread {
public static void main(String args[]) {
new NewThread();// Create a new Thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread : " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main Thread interrupted ");
}
System.out.println("Exiting main thread ");
}
}
> But with only this in the Constructor it does not
> compile.
> I know I have done it wrong by this.t
> With just 't' in the constructor it compiles without
> any error
>
> But the problem is that the new thread does not
> start.
The code you posted compiles for me when I make the change that primet21 suggested. What error do you get when you try it?
Hello !
It says :
Can not resolve symbol.
symbol: Constructor Thread (New Thread, java.lang.String)
location: class java.lang.Thread
t = new Thread(this, "New Thread");
My dear brother
This is what I get with only 'this' in the constructor.
But if I replace it with only 't' in the constructor ; it compiles but still the problem remains.
Don't get the new thread started.
God bless you.
NADEEM.