Java中线程池基本api及其作用

1.线程池相关的类

2.重要类的api及其方法

Executors.newCachedThreadPool() 创建一个可缓存的线程池

Executors.newSingleThreadExecutor();创建一个只有一个线程执行的 不可修改的线程池

 

3.线程工厂ThreadFactory

       就和我们平常使用的一样我们使用各种工厂类帮助我们创建线程,在Executors中我们使用Executors.defaultThreadFactory();静态方法来获得一个defaultThreadFactory类,先来看defaultThreadFactory的获得

Thread thread = threadFactory.newThread( new Runnable() {
			public void run() {
				
			}
		});

 

使用newThread方法就可以不用再new thread来创建线程了

4.使用callable获得返回值 

Callable和Runnbale一样代表着任务,区别在于Callable有返回值并且可以抛出异常

//使用callable<T>对象并且获取返回值和异常
		ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
		Future<String> future = cachedThreadPool.submit(new Callable<String>() {

			@Override
			public String call() throws Exception {
				return Thread.currentThread().getName();
			}
		});
		try {
			System.out.println("名称为"+future.get());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

 

这里需要注意这里的get方法是同步执行的会阻塞主线程

异常捕获

public String call() throws Exception {
				if(true){
					throw new RuntimeException("抛出异常");
				}
				return Thread.currentThread().getName();
			}

5.延迟执行

ScheduledExecutorService newCachedThreadPool = Executors.newScheduledThreadPool(3);
		long millis = System.currentTimeMillis();
		newCachedThreadPool.schedule(new  Runnable() {
			public void run() {
				System.out.println(millis-System.currentTimeMillis());
			}
		}, 1000, TimeUnit.MILLISECONDS);
	}

  

6.线程的关闭方法

    newCachedThreadPool.shutdown();    线程执行完成后关闭
        newCachedThreadPool.shutdownNow();不等待线程执行完成 直接关闭

7.阻塞队列

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值