Java的多線程和線程池的使用
多線程大大提高程序運行效率,我們在開發(fā)過程中經(jīng)常會開啟一個線程來執(zhí)行一些費時的任務(wù)。開啟一個線程有4種方式,在下面的文章我將詳細(xì)的去講解。
繼承Thread
繼承Thread去執(zhí)行任務(wù),確實可以開啟一個線程去執(zhí)行任務(wù),如果經(jīng)常的去開啟一些線程,也會導(dǎo)致系統(tǒng)資源的浪費。
- public static class Mythread extends Thread{
- @Override
- public void run() {
- System.out.println("當(dāng)前線程"+Thread.currentThread().getId());
- int i = 10/2;
- System.out.println("運行結(jié)果"+i);
- }
- }
- //調(diào)用線程。
- public static void main(String[] args) throws ExecutionException, InterruptedException {
- /**thread執(zhí)行方式*/
- Mythread mythread = new Mythread();
- mythread.start();//啟動線程
- System.out.println("main--end");
- }
實現(xiàn)Runnale接口。
- public static class MyRunable implements Runnable {
- @Override
- public void run() {
- System.out.println("當(dāng)前線程"+Thread.currentThread().getId());
- int i = 10/2;
- System.out.println("運行結(jié)果"+i);
- }
- }
調(diào)用。
- /**
- * runable的啟動方式
- */
- MyRunable runable = new MyRunable();
- new Thread(runable).start();
- System.out.println("main--end");
Callable
- /**
- * Callable可以允許有返回值
- */
- public static class Callale01 implements Callable<Integer> {
- @Override
- public Integer call() throws Exception {
- System.out.println("當(dāng)前線程"+Thread.currentThread().getId());
- int i = 10/2;
- System.out.println("運行結(jié)果"+i);
- return i;
- }
- }
調(diào)用。這里需要用callable構(gòu)建futureTask
- /**
- * callale的啟動方式
- */
- FutureTask<Integer> futureTask =new FutureTask<>(new Callale01());
- //取返回結(jié)果。
- Integer i = futureTask.get();
- new Thread(futureTask).start();
- System.out.println("返回結(jié)果是:"+i);
線程池
線程池才是我們java開發(fā)中,經(jīng)常用到一種開啟多線程的方式,線程池,自己去管理線程??梢怨?jié)省系統(tǒng)資源。通常我們會將下面的一些配置寫在一些配置類中
- /**
- * 七大參數(shù)
- * corePoolSize: 1.核心線程數(shù)[一直存在]: 線程池創(chuàng)建好了以后。就準(zhǔn)備就緒的線程數(shù)量。
- * maxinumPoolSize: 2 最大線程數(shù)量
- * keepaliveTime: 存活時間。空閑線程的最大的等待時間。
- * unit 等待時間的單位
- * blockingQueue 阻塞隊列。如果任務(wù)很多就會放在隊列里面,只要有線程空閑了,就會去隊列里面去取。
- * threadFactory :線程的工廠。
- * RejectExecutionHandler :如果隊列滿了。按照我們指定的策略。拒絕執(zhí)行任務(wù)。
- *
- */
- ThreadPoolExecutor executor = new ThreadPoolExecutor(5,100,10,TimeUnit.SECONDS,
- new LinkedBlockingQueue<>(100),
- Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
常見的4種線程池。
1 newCachedThreadPool()
創(chuàng)建一個可緩存的線程池,如果線程池長度超過了處理的需要,可靈活的回收空閑線程。若無可回收。則創(chuàng)建新線程。
- Executors.newCachedThreadPool();
2.newFixedThreadPool(6)
創(chuàng)建一個固定大小的線程池。
3 newScheduledThreadPool()
定時任務(wù)的線程池。
4.newSingleThreadExecutor()
- Executors.newSingleThreadExecutor();