Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Start thread using inner class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Start thread using inner class" Watch "Start thread using inner class" New topic
Author

Start thread using inner class

Pawanpreet Singh
Ranch Hand

Joined: Jun 12, 2005
Posts: 264

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

Joined: Feb 07, 2005
Posts: 643

above code is error free.
dont use start() method inside println.
Pawanpreet Singh
Ranch Hand

Joined: Jun 12, 2005
Posts: 264

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

Joined: Aug 17, 2005
Posts: 26
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
 
 
subject: Start thread using inner class
 
Similar Threads
aboue Runtime.getRuntime().exec() create process
diff between synchronizing on static var when u implement Runnable or extend Thread
Thread functioning help
a.run() and a.start()
thread question