Matt Gerrans
Posts: 1153
Nickname: matt
Registered: Feb, 2002
|
|
Re: Threads
|
Posted: Jun 4, 2002 12:38 AM
|
|
Here is a simple example of two threads communicating asynchronously. The communication is one-way, to make it more clear to follow what is going on. The random timing allows you to run it several times to get an idea of how the communication proceeds when the sender and receiver work at different paces and for varying intervals.
import java.util.*;
public class TalkingThreads
{
public static void main( String [] args )
{
Listener listener = new Listener();
Talker talker = new Talker(listener);
talker.start();
listener.start();
}
}
class Talker extends Thread
{
String [] thingsToSay = { "Hi", "How's it goin'?", "Hey there",
"How do?", "Howdy", "Felicitations",
"Hiya", "Hey", "Yo", "Wutup?", "Hola",
"Bon Jour", "Guten Tag", "Previet" };
private Listener listener;
private static Random randy = new Random();
public Talker( Listener l )
{
listener = l;
}
public void run()
{
long endTime = System.currentTimeMillis() + 5*1000 + randy.nextInt(10*1000);
while( System.currentTimeMillis() < endTime )
{
try
{
Thread.sleep( randy.nextInt( 1000 ) + 100 );
}
catch( InterruptedException ie )
{
System.out.println("Leave me alone, I'm trying to sleep.");
}
talk( listener );
}
System.out.println( "Comment from Talker: I've had enough of this conversation." );
}
public void talk( Listener l )
{
String said = thingsToSay[randy.nextInt( thingsToSay.length )];
l.listen( said );
System.out.println( "Comment from Talker: I just said: " + said );
}
}
class Listener extends Thread
{
private LinkedList messageQueue = new LinkedList();
private static Random randy = new Random();
synchronized public void listen( String msg )
{
messageQueue.add(msg);
}
synchronized public void echoMessage()
{
System.out.print( "Comment from Listner: " );
if( messageQueue.isEmpty() )
System.out.println( "Haven't heard much lately." );
else
System.out.println( "I just heard: " + (String)messageQueue.removeFirst() );
}
public void run()
{
// Only pay attention for a minute:
long endTime = System.currentTimeMillis() + 7*1000 + randy.nextInt(15*1000);
while( System.currentTimeMillis() < endTime )
{
try
{
Thread.sleep( randy.nextInt( 1200 ) );
}
catch( InterruptedException ie )
{
System.out.println("Leave me alone, I'm trying to sleep.");
}
echoMessage();
}
System.out.println( "Comment from Listner: That's what I was going to say." );
}
}
|
|