00001 00002 /** 00003 * The class <code>T1</code> extends <code>Thread</code> class. 00004 * Instance of the <code>T2</code> prints out its signature 00005 * until it gets stopped. It also creates a charged particle pair 00006 * in associated <code>JPWorld</code> context. 00007 * 00008 * @author Mikica B Kocic 00009 */ 00010 public class T1 extends Thread 00011 { 00012 private String signature = "T1: Thread 1"; 00013 00014 /** 00015 * Indicates if thread is (or should be) running 00016 */ 00017 private volatile boolean running = false; 00018 00019 /** 00020 * Indicates that thread is completed 00021 */ 00022 private volatile boolean completed = true; 00023 00024 /** 00025 * Sleep interval for thread in millis. 00026 */ 00027 private int sleepItervalMillis; 00028 00029 /** 00030 * Parent where println() messages are directed to. 00031 */ 00032 protected JPWorld parent; 00033 00034 /** 00035 * Creates a new instance of T1. 00036 * 00037 * @param parent owner of the thread 00038 * @param sleepIntervalSec sleep interval in seconds 00039 */ 00040 public T1( JPWorld parent, float sleepIntervalSec ) 00041 { 00042 this.parent = parent; 00043 this.sleepItervalMillis = (int)( sleepIntervalSec * 1000f ); 00044 } 00045 00046 /** 00047 * Starts the thread. 00048 */ 00049 @Override 00050 public void start () 00051 { 00052 if ( ! completed ) { 00053 return; // Allow only single thread per instance 00054 } 00055 00056 running = true; 00057 completed = false; 00058 super.start (); 00059 } 00060 00061 /** 00062 * Stops the thread. 00063 */ 00064 public void stopThread () 00065 { 00066 running = false; 00067 this.interrupt (); // interrupt ongoing sleep 00068 } 00069 00070 /** 00071 * Interruptible sleep (instead of <code>Thread.sleep</code>). 00072 * 00073 * @param millis - the length of time to sleep in milliseconds. 00074 */ 00075 public void interruptibleSleep( long millis ) 00076 { 00077 try { 00078 Thread.sleep( millis ); 00079 } 00080 catch( InterruptedException ie ) { 00081 /* ignored */ 00082 } 00083 } 00084 00085 /** 00086 * Prints thread's own signature and creates a pair of particles in belonging 00087 * <code>JPWorld</code>'s context every <code>sleepItervalMillis</code>. 00088 */ 00089 @Override 00090 public void run () 00091 { 00092 while( running ) 00093 { 00094 parent.println( signature ); 00095 00096 parent.createPairOfChargedParticles( 1, 10.0 + Math.random () * 5.0 ); 00097 00098 interruptibleSleep( sleepItervalMillis ); 00099 } 00100 00101 completed = true; 00102 } 00103 }