• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Start thread using inner class

 
Pawanpreet Singh
Ranch Hand
Posts: 264
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is wrong with code, i am not able to compile it even?

Can anybody help me?


System.out.println(
new Thread(new Runnable()
{
public void run(){
System.out.println("ONE");
}
}
).start();
);
 
Gowher Naik
Ranch Hand
Posts: 643
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

above code is error free.
dont use start() method inside println.
 
Pawanpreet Singh
Ranch Hand
Posts: 264
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try this...i have done something according to your comments

package threading;

public class ThreadByInner extends Thread{

public ThreadByInner(Runnable r)
{
super(r);
}
/**
*USED an overloaded method here
*
*This is the method of main thread, it will start the new thread
*and hence Thread.currentThread().getName() in below statement gives name
*as "main" instead of "NewThread".....
*Keep one thing in mind, we can get name of a thread, if in run() method,
*so NewThread is being displayed with this.
*/
public String start(String name)
{
super.start();
setName(name);
return Thread.currentThread().getName()+" is the current executing thread";
}

public static void main(String... args)
{

/*
We can create a Thread inside a SOP but can not run, as for that we have to call start() that does not
* has return type void, accept somthing which is string.
*/
System.out.println(new ThreadByInner(new Runnable()
{
public void run(){
System.out.println( Thread.currentThread().getName()+" is the current executing thread");
}
}
).start("NEW THREAD")
);
}
}

----------------------------------
/*
Output is

main is the current executing thread
NEW THREAD is the current executing thread


*/
 
Stephen O'Kane
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you take the semi colon out after the call to start() things begin to look more obvious. You cannot use a semi colon within the method call println(). When you remove the semi colon you will see that the println() method cannot be called with a void (the return type from start()).

Sok
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic