java多线程 简单实例

new Thread的弊端如下:
  a. 每次new Thread新建对象性能差。
  b. 线程缺乏统一管理,可能无限制新建线程,相互之间竞争,及可能占用过多系统资源导致死机或oom。
  c. 缺乏更多功能,如定时执行、定期执行、线程中断。
相比new Thread,Java提供的四种线程池的好处在于:
  a. 重用存在的线程,减少对象创建、消亡的开销,性能佳。
  b. 可有效控制最大并发线程数,提高系统资源的使用率,同时避免过多资源竞争,避免堵塞。
  c. 提供定时执行、定期执行、单线程、并发数控制等功能。 

2、Java 线程池
Java通过Executors提供四种线程池,分别为:
newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程;线程数量无限大,当执行第二个任务时第一个任务已经完成,会复用执行第一个任务的线程,而不用每次新建线程。
newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。
newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

 public static void main(String[] args) {
        ExecutorService executors = Executors.newFixedThreadPool(4);
        Future<String> f1 = executors.submit(new TestCallable("Th1"));
        Future<String> f2 = executors.submit(new TestCallable("th2"));
        Future<?> f3 = executors.submit(t);
        Future<?> f4 = executors.submit(t2);
        try {
            while (true){
                if(f1.isDone() && f2.isDone()){
                    System.out.println("ft:"+f1.get());
                    System.out.println("ft1:"+f2.get());
                    break;
                }
            }
            executors.shutdown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
}
public class TestCallable implements Callable {
    private String tName;

    public TestCallable(String tName) {
        this.tName = tName;
    }

    @Override
    public Object call() throws Exception {
        System.out.println("进入方法!!!"+tName);

        int i = 1;
        for (;i < 10;i++) {
            Thread.sleep(500);
            System.out.println(i + "::" + tName);
        }
        return "tName"+i;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值