62,614
社区成员
发帖
与我相关
我的任务
分享
/**
* 龟兔赛跑---兔子
* @author
* 2017-7-26
*/
public class RabitThread extends Thread{
private int distance;
public RabitThread(String name, int distance){
super(name);
this.distance = distance;
}
public void run() {
long startTime=System.currentTimeMillis();
int i=0;
int n=1;
while (i <= distance) {
try {
//每经过100步再休息一小会
if(i % 1000 == 0){
System.out.println("兔子休息等乌龟第" + (n++) + "次,步数:" + i);
Thread.sleep(1100);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
//步长是250cm 兔子是乌龟速度的250倍
i=i+250;
}
long endTime=System.currentTimeMillis();
System.out.println(getName()+"奔跑"+distance+"cm共耗时:"+(endTime-startTime)+"毫秒");
}
public void setDistance(int distance){
this.distance = distance;
}
public int getDistance(){
return this.distance;
}
}
/**
* 龟兔赛跑---龟
* @author
* 2017-7-26
*/
public class TortoiseThread extends Thread{
private int distance;
public TortoiseThread(String name, int distance){
super(name);
this.distance = distance;
}
public void run() {
long startTime=System.currentTimeMillis();
int i=1;
while (i <= distance) {
try {
//每经过1步再休息一小会,为了模拟两个时间接近,乌龟sleep一下
if(i%1==0){
Thread.sleep(1);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
//步长是1cm
i=i+1;
}
long endTime=System.currentTimeMillis();
System.out.println(getName()+"奔跑"+distance+"cm共耗时:"+(endTime-startTime)+"毫秒");
}
public void setDistance(int distance){
this.distance = distance;
}
public int getDistance(){
return this.distance;
}
}
/**
* 龟兔赛跑
* @author
* 2017-7-26
*/
public class RunTest {
public static void main(String[] args) {
RabitThread rabit = new RabitThread("兔子", 5000);
TortoiseThread tortoise = new TortoiseThread("乌龟",5000);
rabit.start();
tortoise.start();
}
}
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Race {
private static ExecutorService service = Executors.newFixedThreadPool(8);
private static int sleep(){
try{
Thread.sleep(1000);
}catch(InterruptedException e){}
return 1;
}
private static void tortoise(){
try{
Callable<Integer> c = () -> sleep();
final Collection<Callable<Integer>> r = Arrays.asList(c,c,c,c,c);
List<Future<Integer>> results = service.invokeAll(r);
System.out.println("Tortoise won the race!");
}catch(Exception e){
e.printStackTrace();
}
}
private static void hare(){
try{
Callable<Integer> c = () -> sleep();
final Collection<Callable<Integer>> r = Arrays.asList(c,c,c,c,c);
List<Future<Integer>> results = service.invokeAll(r);
System.out.println("hare won the race!");
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
service.submit(() -> hare());
service.submit(() -> tortoise());
Thread.sleep(5000);
service.shutdown();
}
}