dcsimg
how to access/control one thread from within another one?
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   John_Wong
Posted On:   Tuesday, August 24, 2004 05:21 PM

is there any mechanism to communicate between two threads? further, is it possible to stop/re-start one thread from within another thread, if both of them are already running?

Re: how to access/control one thread from within another one?

Posted By:   Edward_Harned  
Posted On:   Thursday, August 26, 2004 09:45 AM

Define a common storage area with a class. The class contains references to
each thread so you can call methods on each thread.



public
class
Common {


    MyThread mt1 =
null
;


    MyThread mt2 =
null
;



    String work1 =
null
;



    int
a1, a2, a3;


}



Instantiate that class as well as the threads you need.:



Common myCommon = new
Common();



work1 = new
String(
"This is work area");



a1 = 1;


a2 = 2;


a3 = 3;




// pass a reference to the common storage to each thread

mt1 =
new
MyThread(myCommon);

mt2 =
new
MyThread(myCommon);



mt1.start();


mt2.start();


 


Now each thread  has access to the common storage and access to instance
methods on each thread.



public
class
MyThread
extends
Thread {


    Common myCommonArea =
null;



public MyThread (Common commonArea) {



    myCommonArea = commonArea;


}

}



The caveat is to synchronize. Each thread must synchronize on the common area
before referencing/changing any field in Common;


    synchronized (myCommonArea) 




        {}


In order to stop any thread you must follow the suggestions outlined in "why
thread.stop() is deprecated" in the javadoc.

About | Sitemap | Contact