Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread Vs. Runnable

 
Himanshu Jhamb
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All.
Here's my Question...
If I want to create two threads on the same Object, can I do so by extending the Thread class ?
Here's why I ask this question...
My sample code...
Case 1 - Extending Thread class
-------------------------------
public class myThread extends Thread {
public void run() {
synchronized(this)
{
// Some code... }
}
}
public static void main(String[] args) {
Thread t1 = new myThread(); // Thread #1
Thread t2 = new myThread(); // Thread #2 BUT on a different object, not the same one as the first one.
t1.start();
t2.start();
}
}
Case 2 : Implementing Runnable
------------------------------
class MyRunnable implements Runnable {
public void run() {
synchronized(this)
{
// Some code... }
}
}
public class MyThread {
public static void main(String[] args) {
MyRunnable myRun = new MyRunnable();
Thread t1 = new Thread(myRun); // New Thread on myRun object
Thread t2 = new Thread(myRun); // Another Thread on the SAME myRun object
t1.start();
t2.start();
}
}
------------------------------------------------
In both these code samples, I want to synchronize a block of code on the object referenced by 'this'. In order to achieve object synchronization, I need to have multiple threads on the SAME OBJECT ( At least thats what my concepts are about synchronization ). Hence, my Question ... Is there a way I can create 2 or more new threads on the same object using Thread class ? If one takes a look at the Thread class, although there is a constructor that takes a Runnable reference... which makes it possible for Case 2 to work the way I want it to.
Am I missing something in the Thread class ? I am sure I am... 'cause I know that although Runnable is a better way of creating threads, the second way of extending from the Thread class works as well.
thanks for your help in advance.
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes it is true, the two threads in the first example are not properly synchronized. It is necessary to be aware of which object "this" is pointing to when synchronizing. This one of the possible reasons to use an object solely as a lock for synchronization instead of "this".
 
Dave Landers
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But if the entire run() method of MyRunnable is synchronized, what's the point of having two threads? Only one will run at a time.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic