Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
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

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
public class ThreadDiff1{
public static void main(String[] args){
System.out.println("Start of main");
//CASE 1::
Thread t1=new Thread();
Thread t2=new Thread();
//CASE 2::
MyThreadClass mt1=new MyThreadClass();
MyThreadClass mt2=new MyThreadClass();

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

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

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: 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%
Vijitha Kumara

Joined: Mar 24, 2008
Posts: 3902

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 ]

[How to ask questions] [Twitter]
I agree. Here's the link:
subject: Thread object creation
It's not a secret anymore!