| 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
|
|
|