Executors.newFixedThreadPool 实验结果

、Executors在于java.util.comcurrent.包下,Executors.newFixedThreadPool(n)创建容器大小为n的线程池,表示正在执行中的线程只有n个,

实践代码如下:

public class TestExecute {
 
    public static void main(String[] args) {
        Executor exe = Executors.newFixedThreadPool(2);
 
        for (int i = 0; i < 3; i++) {
            ExeThreads ex = new ExeThreads();
            exe.execute(ex);
 
        }
 
    }
 
}
 
class ExeThreads implements Runnable {
 
    @Override
    public void run() {
        try {
            System.out.println("run start-----------------" + System.currentTimeMillis());
            Thread.sleep(15 * 1000);
            System.out.println("run end-----------------" + System.currentTimeMillis());
 
        }
        catch (InterruptedException e) {
 
            e.printStackTrace();
        }
 
    }
 
}
实验结果如下:

 

事例总结:线程池大小为2,但是要执行的线程是3个。所以正在执行的线程只有2个,正在执行的2个线程的开始时间为1536907573338,2个线程的结束时间为1536907588338,第3个线程的开始时间,刚刚好是前面2个线程执行结束时间。
 

package 操作系统实验二; import java.util.concurrent.*; class PrintTask implements Runnable { private char ch; private Semaphore currentSemaphore; private Semaphore nextSemaphore; public PrintTask(char ch, Semaphore currentSemaphore, Semaphore nextSemaphore) { this.ch = ch; this.currentSemaphore = currentSemaphore; this.nextSemaphore = nextSemaphore; } public void run() { try { for (int i = 0; i < 3; i++) { currentSemaphore.acquire(); System.out.print(ch); nextSemaphore.release(); } } catch (InterruptedException e) { e.printStackTrace(); } } } public class Main { public static void main(String[] args) { Semaphore semaphoreA = new Semaphore(1); Semaphore semaphoreB = new Semaphore(0); PrintTask printA = new PrintTask('A', semaphoreA, semaphoreB); PrintTask printB = new PrintTask('B', semaphoreB, semaphoreA); ExecutorService executorService = Executors.newFixedThreadPool(2); // 顺序1:AAAB executorService.execute(printA); executorService.execute(printA); executorService.execute(printA); executorService.execute(printB); // 顺序2:BBAA //executorService.execute(printB); //executorService.execute(printB); //executorService.execute(printA); //executorService.execute(printA); // 顺序3:AABA //executorService.execute(printA); //executorService.execute(printA); //executorService.execute(printB); //executorService.execute(printA); // 顺序4:ABAA //executorService.execute(printA); //executorService.execute(printB); //executorService.execute(printA); //executorService.execute(printA); executorService.shutdown(); } }
06-01
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值