aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Thread object creation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Thread object creation" Watch "Thread object creation" New topic
Author

Thread object creation

Sekhar Choudary
Ranch Hand

Joined: May 03, 2008
Posts: 57
Hi, Source code is as follows
class MyThreadClass extends Thread{
public void run(){
for(int i=1;i<=3;i++)
System.out.println("Running By "+Thread.currentThread().getName()); }//run
}//class
public class ThreadDiff1{
public static void main(String[] args){
System.out.println("Start of main");
//CASE 1::
Thread t1=new Thread();
t1.start();
Thread t2=new Thread();
t2.start();
//CASE 2::
MyThreadClass mt1=new MyThreadClass();
mt1.start();
MyThreadClass mt2=new MyThreadClass();
mt2.start();

//CASE 3::
MyThreadClass obj_t1=new MyThreadClass();
MyThreadClass obj_t2=new MyThreadClass();
Thread obt1=new Thread(obj_t1);
obt1.start();
Thread obt2=new Thread(obj_t2);
obt2.start();
System.out.println("End of main");
}//main
}//class

What are the differences between CASE 2 and 3 , also What will be default thread names given to each of these threads, can we guareentee for any paricular thread naming order of these by jvm?
Are there any similar ways to create threads .
Sid Murrey
Ranch Hand

Joined: Jul 07, 2008
Posts: 58
Next time preserve the indentation by using the UBB CODE tags:


[ July 30, 2008: Message edited by: Sid Murrey ]
Ireneusz Kordal
Ranch Hand

Joined: Jun 21, 2008
Posts: 423
Hi,

In case 1 thread is created by creating a new class (MyThreadClass), implementing (overriding) it's run() method, creating object of this class and finally calling the start() method of this object.

In Case 2 thread object is created directly using Thread class, but by invoking Thread(Runnable obj) constructor. In this case the thread will execute run() method of obj, not it's own run() method. You have to remember that Thread class implements Runnable interface, so objects of Thread class can be used as 'Runnable' objects to start thread this way.

Here: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#Thread() you find rules for naming the threads.
Milan Sutaria
Ranch Hand

Joined: Jul 10, 2008
Posts: 122
i think case 2 & 3 are same (practically).
the overriding method in the MyThreadClass will be run in both the cases


SCJP 6 83%
Working on SCWCD/OCPJWCD
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3832

yes in CASE 2 & CASE 3 doing the same thing (though it may behave differently considering the execution order).
[ July 31, 2008: Message edited by: Vijitha Kumara ]

SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Thread object creation