Java多线程&线程池

  • 创建线程的两种方式

    • 在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();
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

良月柒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值