线程池实现方式

183 阅读1分钟

实现多线程的方法

  1. 继承 Thread 类创建线程;
public class TestThread extends Thread{
 
    @Override
    public void run() {
        for(int i=1; i<=3; i++) {
            System.out.println(this.getName());
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
 public static void main(String args[]) {
        TestThread testThread = new TestThread();
        TestThread testThread1 = new TestThread();
        testThread.setName("testThread");
        testThread1.setName("threadThread1");
        testThread.start();
        testThread1.start();
    }

  1. 实现 Runnable 接口创建线程;
package basic;
 
public class TestRunnable implements Runnable{
    // 实现 Runnable接口 中的run()方法
    @Override
    public void run() {
        int times = 5;
        for(int i=0; i<times; i++) {
            System.out.println(Thread.currentThread().getName());
            try {
                Thread.sleep(100);
            }
            catch(InterruptedException ie){
                ie.printStackTrace();
            }
        }
    }
    public static void  main(String args[]) {
        TestRunnable runn = new TestRunnable();
        // 创建线程
        Thread dog = new Thread(runn,"小狗");
        Thread cat = new Thread(runn,"小猫");
        // 启动线程
        dog.start();
        cat.start();
    }
}
  1. 通过 Callable 和 Future 创建线程;(少用)
  2. 通过线程池创建线程。

在开发中经常碰到这样一种情况,就是使用一个已经继承了某一个类的子类创建线程,由于一个类不能同时有两个父类,所以不能用继承 Thread 类的方式,那么就只能采用实现 Runnable接口的方式。可以避免由于 Java 的单继承带来的局限性。 但是1,2,3,在开发中不常用,因为这样会难以维护。

更多是通过线程池来实现

  • 1.降低资源消耗:通过重复利用已创建的线程降低线程创建和销毁造成的消耗。
  • 2.提高响应速度:当任务到达时,可以不需要等待线程创建就能立即执行。
  • 3.提高线程的可管理性:线程是稀缺资源,如果无限制的创建,不仅会消耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一的分配,监控和调优。

设置线程参数设置

图片.png

图片.png

图片.png

图片.png