Thomas SMETS
Posts: 307
Nickname: tsmets
Registered: Apr, 2002
|
|
Re: threads
|
Posted: May 3, 2002 3:52 PM
|
|
This should do : http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=27&t=000619 Otherwise check this
package test.lang;
import org.apache.log4j.Category;
import org.apache.log4j.BasicConfigurator;
import java.util.Random;
/**
* The purpose of this class is to :
*
* Show how we can use threaded inner classes safely accessing the
* "carrying/supporting" class attributes !
*
* @author <a href="mailto:tsmets@altern.org">Thomas SMETS, Brussels</a>
* @version 0.1.15 pre-final
*/
class Parent
{
Category log = Category.getInstance (Parent.class);
Random random = new Random (System.currentTimeMillis ());
Object o;
String SharedObject = null;
boolean isBusy = false;
public static final long MAX_ITER = 200;
Inner i1, i2;
Parent()
{
log.info ("Parent created");
i1 = new Inner(1);
i2 = new Inner(2);
o = new Object ();
}
public void go ()
{
log.info ("Parent::go( )");
i1.start ();
i2.start ();
}
public void getBusyFlag(int callerNbr)
{
log.info ("Requesting the busy-flag (Thread is " + callerNbr + ")");
synchronized (o)
{
while (isBusy)
{
try
{
log.info ("Thread " + callerNbr + " is waitng");
o.wait ();
}
catch (Exception ex)
{
log.info ("Thread " + callerNbr + " wait has been disturbed");
}
}
if (!isBusy)
{
isBusy = true;
log.info ("Busy flag has been given to Thread : " + callerNbr);
return;
}
}
}
public boolean isFlagBusy () { return isBusy; }
public void releaseFlag(int callerNbr)
{
synchronized (o)
{
log.info ("Releasing the flag : " + callerNbr);
isBusy = false;
o.notifyAll();
}
}
public static void main(String[] args)
{
BasicConfigurator.resetConfiguration ();
BasicConfigurator.configure ();
new Parent().go();
}
class Inner
extends Thread
{
int Nbr;
Category ilog = null;
Inner ()
{
Nbr = 0;
ilog = Category.getInstance (Inner.class);
}
Inner (int i)
{
this();
Nbr = i;
}
public void run()
{
ilog.info (Nbr + " Inner::run()");
while(true)
{
getBusyFlag(Nbr);
try
{
if (SharedObject != null)
ilog.fatal ("SharedObject is not null (Thread : "+ Nbr +"). First part is "
+ SharedObject.substring ( 0,
(SharedObject.length ()<20)?
SharedObject.length ():
20) );
for (int i = 0; i<MAX_ITER; i++)
{
SharedObject += new Integer (Nbr).toString ();
try
{
Thread.sleep (20);
}
catch (Exception ex)
{
}
}
SharedObject = null;
releaseFlag(Nbr);
}
catch (Exception ex)
{
ilog.warn ("I have been woken up (Thread : "+ Nbr +"). Exception is "
+ ex.getClass ().getName () );
}
}
}
} // End of inner class
}
Should help !
Please note that the version I posted on the javaranch is OKay... This one is a Copy / Paste from my IDE (It may not be fresh anymore :-D)
Thomas SMETS, SCJP2 - BRussels
|
|