package threadTEST;
import java.time.Instant;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class GeneralInterrupt extends Thread {
private String label;
public GeneralInterrupt(String label) {
this.label = label;
}
public void run() {
System.out.println(label + "start");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(label + "end");
if (label.equals("t5")) {
System.out.println(Instant.now());
}
}
public static void main(String args[]) throws InterruptedException {
ExecutorService pool = Executors.newSingleThreadExecutor();
GeneralInterrupt t1 = new GeneralInterrupt("t1");
GeneralInterrupt t2 = new GeneralInterrupt("t2");
GeneralInterrupt t3 = new GeneralInterrupt("t3");
GeneralInterrupt t4 = new GeneralInterrupt("t4");
GeneralInterrupt t5 = new GeneralInterrupt("t5");
System.out.println(Instant.now());
pool.execute(t1);
pool.execute(t2);
pool.execute(t3);
pool.execute(t4);
pool.execute(t5);
}
}
使用Java的三种线程池,测试运行效果。注释的那行语句可以更改,改成
newFixedThreadPool,newSingleThreadExecutor,newCachedThreadPool
1.single thread
因为每次只运行一个线程,所以是有序的,如果对顺序有要求可以考虑这种,但是时间代价很大。lab6中主要是提高吞吐率而不是公平性,所以不选用这种。
2.fixed thread
ExecutorService pool = Executors.newFixedThreadPool(3);
限制了同时运行的线程的数量,这也可以在一定程度上增加公平性,不过时间代价有点大。但是在lab6中,猴子是按批次生成的,每次生成N个,所以我觉得可以考虑这种方法。但还需要之后的调试来确定。
3.cached thread
ExecutorService pool = Executors.newCachedThreadPool();
通过阅读源码我发现cachedthreadpool中允许的最大线程是0x7fffffff,所以可以理解为很大的fixedthreadpool
不出所料,这种方法运行时间是最短的。相比之下,我更倾向于用这种线程池来处理猴子线程。而且线程池内部是用队列来存储线程的,我觉得一定程度上保证了公平性。如果猴子速度差不多,那么公平性可以保证。如果每次都是老猴子先上桥,就没办法了,总不能让年轻猴子一直在后面等吧?