线程池 ExecutorService execute 异步执行

package com.cfets.cfib.thread.general;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 使用ExecutorService线程池异步执行
 * 执行无返回结果时用execute方法
 * Created by cfets on  2018/6/26.10:33
 */
public class ThreadTest {

    public static void main1(String[] args) {
        ExecutorService cachedThreadPool = Executors.newFixedThreadPool(50);
//      ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

        cachedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("3秒等待开始");
                    Thread.sleep(3 * 1000);
                    System.out.println("等待结束");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        System.out.println("--------------->");
    }

    // jdk 1.8写法
    public static void main(String[] args) {
        ExecutorService cachedThreadPool = Executors.newFixedThreadPool(50);
        cachedThreadPool.execute(() -> proexect());
        System.out.println("--------------->");
    }

    public static void proexect() {
        try {
            System.out.println("3秒等待开始");
            for (int i = 0; i < 3; i++) {
                Thread.sleep(1 * 1000);
                System.out.println(i);
            }
            System.out.println("等待结束");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

猜你喜欢

转载自www.cnblogs.com/xiaolei2017/p/9240123.html