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