Java多线程&线程池

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lkp1603645756/article/details/81456504
  • 创建线程的两种方式

    • 在Thread子类覆盖的run方法中编写运行代码
    • 在传递给Thread对象的Runnable对象的run方法中编写代码
    • 总结:查看Thread类的run()方法的源代码,可以看到其实者两种方式都是在调用Thread对象的run方法,如果Thread类的run()方法没有被覆盖,并且为该Thread对象设置了一个Runnable对象,该run方法会调用Runnable对象的run方法。
    • 多线程机制会提高程序的运行效率吗?
      • 不会,因为CPU只有一个,CPU切换线程需要时间。
  • 定时器的应用

    • Timer类
    • TimerTask类
  • 线程池

    • Executors

创建3个线程,有10个任务需要执行。

/**
 * 作者:LKP
 * 时间:2018/8/13
 */
public class ThreadPoolTest {
    public static void main(String[] args){
        ExecutorService threadPool = Executors.newFixedThreadPool(3);//创建3个线程
        for (int i = 1; i <= 10; i++) {
            final int task = i;
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    for (int j = 1; j <= 10; j++) {
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName()+" is looping of " + j + " for task to "+task);
                    }
                }
            });
        }
        System.out.println("all of 10 tasks have committed!");
        threadPool.shutdown();
    }
}

猜你喜欢

转载自blog.csdn.net/lkp1603645756/article/details/81456504