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.