i know this is a very basi doubt but just wanted to clarify. We know that for making a thread run, you call the start method and then invoke the run() method. But can a thread start running without callin the start() method. For example the foll code compiles cleanly. public class NiceThreads implements Runnable { public void run() { while(true) { } }
public static void main(String args[]) { NiceThreads nt1 = new NiceThreads(); NiceThreads nt2 = new NiceThreads(); NiceThreads nt3 = new NiceThreads(); nt1.run(); nt2.run(); nt3.run(); } } I thought it wont compile as you havent set the start() method. Please clarify.
Hi What u have done is simply extending a class and then creating its instnace, u are not actually creating a thread if u are extending a thread u must call its start method as well as u must create an instance of that thread and then call start method on that particular thread hope it help. Although i am also new in the topic of thread please send me some ideas on which basically the exam questions are based. Thanx. Nisheeth.
Just to throw in my 2 cents. If you call the run method of a Thread object directly it is the same as calling any other method of any other object - the method will run in the current thread of execution. Calling the start method of a Thread object registers it with the scheduler and does some other behind the scenes work to make it work as a seperate execution process. Notice the difference in the capitalization a Thread is an object of type Thread or that extends type Thread, while a thread is seperate execution process. I've seen several questions of this type on the mocks I've taken so it might be a type you can expect to see on the scjp. hope that helps Dave
Hi, Dave has given a good explanation. I just modified your code, to see what happens if you start the thread using start() and what happens if you directly run() the thread. First run() it directly.
u have just created 3 threads and put them in an infinite loop.For all 3threads to get c.p.u time put Thread.sleep()inthe while loop s.t. the thread gives time for the other two to execute.Correct me if i am wrong. Vedhas
You can use Thread.yield() causing a Thread to move into a ready to run state, giving other Threads the opportunity to run. You could call Thread.sleep() which puts your Thread into sleep state, but you don't need to in this instance. Kind regards, james hoskins.
Nisheeth Kaushal
Ranch Hand
Joined: Jul 20, 2001
Posts: 87
posted
0
Hi Friends, Great discussion, i was week in thread but slowly the concept is getting clear. Thanx. Nisheeth.