【Java】线程创建方式:Callable接口 / 使用线程池
生活随笔
收集整理的這篇文章主要介紹了
【Java】线程创建方式:Callable接口 / 使用线程池
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
面試題:創(chuàng)建多線程有有哪幾種方式?
回答:4種。
- 實現(xiàn)Runnable接口(重寫Run方法)
- 繼承Thread類
- 實現(xiàn)Callable接口(重寫Call方法,與Run不同的是,Call方法有返回值)
- 使用線程池
JDK5.0新增創(chuàng)建線程方式一:實現(xiàn)Callable接口
方式二:使用線程池
package com.atguigu.java2;import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor;/*** 創(chuàng)建線程的方式四:使用線程池** 好處:* 1.提高響應(yīng)速度(減少了創(chuàng)建新線程的時間)* 2.降低資源消耗(重復(fù)利用線程池中線程,不需要每次都創(chuàng)建)* 3.便于線程管理* corePoolSize:核心池的大小* maximumPoolSize:最大線程數(shù)* keepAliveTime:線程沒有任務(wù)時最多保持多長時間后會終止** 面試題:創(chuàng)建多線程有幾種方式?四種!*/class NumberThread1 implements Runnable {@Overridepublic void run() {for (int i = 0; i <= 100; i++) {if (i % 2 == 0) {System.out.println(Thread.currentThread().getName() + ": " + i);}}} }class NumberThread2 implements Runnable {@Overridepublic void run() {for (int i = 0; i <= 100; i++) {if (i % 2 != 0) {System.out.println(Thread.currentThread().getName() + ": " + i);}}} }public class ThreadPool {public static void main(String[] args) {//1. 提供指定線程數(shù)量的線程池ExecutorService service = Executors.newFixedThreadPool(10);ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;//設(shè)置線程池的屬性 // System.out.println(service.getClass()); // service1.setCorePoolSize(15); // service1.setKeepAliveTime();//2.執(zhí)行指定的線程的操作。需要提供實現(xiàn)Runnable接口或Callable接口實現(xiàn)類的對象service.execute(new NumberThread1());//適合適用于Runnableservice.execute(new NumberThread2());//適合適用于Runnable// service.submit(Callable callable);//適合使用于Callable//3.關(guān)閉連接池service.shutdown();}}總結(jié)
以上是生活随笔為你收集整理的【Java】线程创建方式:Callable接口 / 使用线程池的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Java】线程通信的例子:用两个线程打
- 下一篇: java美元兑换,(Java实现) 美元