Java 线程池的理解

           线程池是一个容器,这个容器中预先创建了很多个线程。如果要执行任务,直接使用这个容器中的线程去执行就可以了。
 并且这个线程池中的线程,可以复用。执行完一个任务后,可以继续执行其他任务。

           

public class Demo01ThreadPool {
    public static void main(String[] args) {
        //调用Executorsnew fixedthreadpool方法获取一个线程池
        ExecutorService pool = Executors.newFixedThreadPool(2);
        //调用submit 传递runnab接口实现类对象,使用线程池里的线程执行该任务
        pool.submit(new MyRunnable());
        pool.submit(new MyRunnable());
        pool.submit(new MyRunnable());

        //销毁线程池
        pool.shutdown();

    }
}
//runnable 接口的实现类,该类是一个任务类。作为任务传参进线程池。
public class MyRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + " hello");
        }

    }
}

      


猜你喜欢

转载自blog.csdn.net/qq_28761767/article/details/81038952
今日推荐