共计 2203 个字符,预计需要花费 6 分钟才能阅读完成。
问题:请用多线程基本知识实现两种状况下的煮饭、筹备
菜(买菜、洗菜)、炒菜、开始吃饭的性能。1、筹备菜 (买菜、洗菜):1 秒,
炒菜:2 秒,煮饭:5 秒 2、筹备菜 (买菜、洗菜):1 秒,炒菜:8 秒,煮饭:
5 秒。阐明:只有煮饭实现、筹备菜、炒菜实现,能力开始吃饭,两种状况
下,在尽量短的工夫内实现所有动作。
办法:通过 FutureTask + Callable + 线程状态的判断加以实现
煮饭类
package com.high.currency11;
import java.util.concurrent.Callable;
public class Rice implements Callable {
@Override
public Rice call() throws Exception {System.out.println("开始煮饭");
Thread.sleep(5000); // 模仿煮饭工夫
System.out.println("煮饭实现");
return new Rice();}
}
买菜洗菜类
package com.high.currency11;
import java.util.concurrent.Callable;
public class Vegetable implements Callable {
@Override
public Vegetable call() throws Exception {System.out.println("开始买菜、洗菜");
Thread.sleep(1000); // 模仿买菜,洗菜工夫
System.out.println("买菜、洗菜已实现");
return new Vegetable();}
}
炒菜类
package com.high.currency11;
import java.util.concurrent.Callable;
public class Cook implements Callable {
@Override
public Cook call() throws Exception {System.out.println("开始炒菜");
// 模仿炒菜工夫
Thread.sleep(8000);
Cook cook = new Cook();
System.out.println("炒菜结束");
return cook;
}
}
吃饭类
package com.high.currency11;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Dinner {public static void haveDinner() throws InterruptedException, ExecutionException {Rice rice = new Rice();
FutureTask<Rice> riceTask = new FutureTask(rice);
Thread rThread = new Thread(riceTask);
rThread.start();
Vegetable veg = new Vegetable();
FutureTask vegTask = new FutureTask(veg);
Thread vThread = new Thread(vegTask);
vThread.start();
vThread.join();
Cook cook=new Cook();
FutureTask<Cook> cookTask = new FutureTask(cook);
new Thread(cookTask).start();
if(!cookTask.isDone()){System.out.println("菜没炒好,就持续等吧");
}
if(!riceTask.isDone()){System.out.println("饭没煮好,就持续等吧");
}
Rice riceResult= riceTask.get();
Cook cookResult=cookTask.get();
if(null!=riceResult&&null!=cookResult) {System.out.println("菜炒好了,饭也煮好了,大家一起吃饭吧");
}
}
}
测试类
package com.high.currency11;
import java.util.concurrent.ExecutionException;
public class Test {public static void main(String[] args) {long startTime = System.currentTimeMillis();
try {Dinner.haveDinner();
} catch (InterruptedException e) {e.printStackTrace();
} catch (ExecutionException e) {e.printStackTrace();
}
System.out.println("整个过程,共耗时" + (System.currentTimeMillis() - startTime) + "ms");
}
}
测试后果
开始煮饭
开始买菜、洗菜
买菜、洗菜已实现
菜没炒好,就持续等吧
饭没煮好,就持续等吧
开始炒菜
煮饭实现
炒菜结束
菜炒好了,饭也煮好了,大家一起吃饭吧
整个过程,共耗时 9009ms
github
正文完