2010年7月21日 星期三

Java multi thread 的 sample

Horse.java

import java.lang.Thread;

class Horse extends Thread {
final int MAX_DISTANCE = 600;
int RaceDistance = 400;
int CurrentDistance = 0;
long RaceTime = 0L;

// Constructors
public Horse( ) {
super( );
}

public Horse(String name) {
super(name);
}

public Horse(String name, int distance) {
super(name);
RaceDistance = (distance < MAX_DISTANCE)? distance: MAX_DISTANCE;
}

public void run( ) {
long begin = 0L, end = 0L;
begin = System.currentTimeMillis( );
while (CurrentDistance <= RaceDistance) {
CurrentDistance += Math.floor(Math.random( ) * 10);
System.out.println(getName( ) + ": " + CurrentDistance);
try {
sleep((long)(Math.random( ) * 1000));
} catch (InterruptedException e) {}
}
end = System.currentTimeMillis( );
RaceTime = end - begin;
}//end of run

public int getCurrentDistance( ) {
return CurrentDistance;
}
public long getRaceTime( ) {
return RaceTime;
}
}//end of class


----------------- 我是分隔線 --------------------
RaceHorse.java

public class RaceHorse {

public static void main(String[ ] args) {
Horse Rubby = new Horse("Rubby", 40);
Horse Lisa = new Horse("Lisa", 40);
Rubby.start( );
Lisa.start( );
while (Rubby.isAlive( ) || Lisa.isAlive( )) {
// Do nothing, just wait for the end.
}
if (Rubby.getRaceTime( ) < Lisa.getRaceTime( ))
System.out.println("Rubby win!! Record: " + Rubby.getRaceTime( ) + " ms");
else if (Rubby.getRaceTime( ) > Lisa.getRaceTime( ))
System.out.println("Lisa win!! Record: "+ Lisa.getRaceTime( ) + " ms");
else
System.out.println("Deuce! Record: "+ Rubby.getRaceTime( ));
}//end of main

}//end of class



沒有留言:

張貼留言