• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread object creation

 
Sekhar Choudary
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Next time preserve the indentation by using the UBB CODE tags:


[ July 30, 2008: Message edited by: Sid Murrey ]
 
Ireneusz Kordal
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i think case 2 & 3 are same (practically).
the overriding method in the MyThreadClass will be run in both the cases
 
Vijitha Kumara
Bartender
Posts: 3914
9
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic