前言,基础线程机制:Executor管理多个异步任务的执行、Daemon守护线程、sleep()、yield()
一、Executor:
1.newCachedThreadPool(),一个任务创建一个线程
ExecutorService executorService = Executors.newCachedThreadPool(); executorService.execute(()->{ //TODO do sth. }); executorService.shutdown();
2.newFixedThreadPool(num),所有任务使用固定num大小的线程
CountDownLatch countDownLatch = new CountDownLatch(clientSize); ExecutorService executorService = Executors.newFixedThreadPool(clientSize); IntStream.range(0,clientSize).forEach(i -> executorService.submit(()->{ //TODO do sth. countDownLatch.countDown(); }) ); countDownLatch.await(); executorService.shutdown();
>>> 输出效果:[clientSize]个线程并发执行//TODO do sth.
3.newSingleThreadExecutor(),相当于newFixedThreadPool(1)
ExecutorService executorService2 = Executors.newSingleThreadExecutor(); executorService2.shutdown();
二、Daemon
// Daemon守护线程。当所有非守护线程结束时,程序终止,同时杀死所有守护线程。main()属于非守护线程 public void m2(){ Thread t1 = new Thread(()->{ //TODO do sth. }); // 通过setDaemon设置该线程td为守护线程 t1.setDaemon(true); }
三、sleep()
// 基础线程机制:Thread.sleep(ms) public void m3(){ try{ Thread.sleep(3000); } catch (InterruptedException e) { throw new RuntimeException(e); // 因为异常不能跨线程传播回main()中,因此必须在本地进行处理 } }
四、yield()
// 基础线程机制:yield(),对静态方法Thread.yidld()的调用声明了当前线程已经完成了生命周期中的最重要部分,可切换给其他线程执行。只是对线程调度器的一个建议 public void m4(){ Thread.yield(); }
标签:do,java,Thread,线程,sleep,机制,executorService,守护 From: https://www.cnblogs.com/jinziguang/p/17235380.html