Java/Multithreading

Advertisement


Question
Hi sir!
my doubt  is in java.My doubt is on creating thread by implementing runnable interface.
Please see the below programme.
In below programme I have implemented the class countdowneven from Runnable.
In main method I am passing the object of countdown even to constructor of thread class.
Why should we pass the  object of countdowneven to constructor of thread class?
What operations will be performed by Thread class constructor on object of countdowneven?
.-----------------------------------------------------------
class thread
{
public static void main(String args[ ])
{
Thread ce=new Thread (new countdowneven());
ce.start();
}
}
class countdowneven implements Runnable
{
public void run()
{
for(int i=10;i>1;i=i-2)
{
System.out.println(i);
}
}
}
------------------------------------------------------------------
Output:
10
8
6
4
2

Answer
The Thread class constructor simply stores the object you give it.
When you call start on the Thread, it will start a new thread which will invoke the run() method of the instance you passed it in the constructor.

Please look at the Thread class in the Javadocs for more details:
http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html

Java

All Answers


Answers by Expert:


Ask Experts

Volunteer


Artemus Harper

Expertise

I have a Masters in computer science. I can answer questions on core J2SE, swing and graphics. Please no questions about JSP or J2ME.

Experience

I have experience in Core Java, good background in Java swing/gui, some experience with JNI, Java reflection. Some experience in bio-informatics. Basics in c++ and c#

Organizations
Washington State University

Education/Credentials
MS in Computer Science from Washington State University and a BS in Mathematics and Computer Science from Central Washington University.

©2016 About.com. All rights reserved.