当前位置:首页 > 应用开发

Java的多线程和线程池的使用

多线程大大提高程序运行效率,多的使我们在开发过程中经常会开启一个线程来执行一些费时的线程任务。开启一个线程有4种方式,和线在下面的程池文章我将详细的去讲解。

继承Thread

继承Thread去执行任务,多的使确实可以开启一个线程去执行任务,线程如果经常的和线去开启一些线程,也会导致系统资源的程池浪费。

public static class Mythread extends Thread{          @Override         public void run() {              System.out.println("当前线程"+Thread.currentThread().getId());             int i = 10/2;             System.out.println("运行结果"+i);         }     } //调用线程。多的使 public static void main(String[] args) throws ExecutionException,线程 InterruptedException {          /**thread执行方式*/         Mythread mythread = new Mythread();         mythread.start();//启动线程         System.out.println("main--end"); } 

实现Runnale接口。

public static class MyRunable implements Runnable {      @Override     public void run() {          System.out.println("当前线程"+Thread.currentThread().getId());         int i = 10/2;         System.out.println("运行结果"+i);     } } 

调用。和线

/**  * runable的程池启动方式  */ MyRunable runable = new MyRunable(); new Thread(runable).start(); System.out.println("main--end"); 

Callable

/**  * Callable可以允许有返回值  */ public static class Callale01 implements Callable<Integer> {      @Override     public Integer call() throws Exception {          System.out.println("当前线程"+Thread.currentThread().getId());         int i = 10/2;         System.out.println("运行结果"+i);         return i;     } } 

调用。这里需要用callable构建futureTask

/**  * callale的多的云服务器使启动方式  */ FutureTask<Integer> futureTask =new FutureTask<>(new Callale01()); //取返回结果。 Integer i = futureTask.get(); new Thread(futureTask).start(); System.out.println("返回结果是线程:"+i); 

线程池

线程池才是我们java开发中,经常用到一种开启多线程的和线方式,线程池,自己去管理线程。可以节省系统资源。通常我们会将下面的一些配置写在一些配置类中

/**  * 七大参数  * corePoolSize: 1.核心线程数[一直存在]: 线程池创建好了以后。就准备就绪的线程数量。  * maxinumPoolSize: 2 最大线程数量  * keepaliveTime: 存活时间。空闲线程的最大的等待时间。  * unit  等待时间的单位  * blockingQueue 阻塞队列。如果任务很多就会放在队列里面,只要有线程空闲了,就会去队列里面去取。云服务器提供商  * threadFactory :线程的工厂。  * RejectExecutionHandler :如果队列满了。按照我们指定的策略。拒绝执行任务。  *  */  ThreadPoolExecutor executor = new ThreadPoolExecutor(5,100,10,TimeUnit.SECONDS,           new LinkedBlockingQueue<>(100),                                                     Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy()); 

常见的4种线程池。

1 newCachedThreadPool()

创建一个可缓存的线程池,如果线程池长度超过了处理的需要,可灵活的回收空闲线程。若无可回收。则创建新线程。

Executors.newCachedThreadPool(); 

2.newFixedThreadPool(6)

创建一个固定大小的线程池。

3 newScheduledThreadPool()

定时任务的线程池。

4.newSingleThreadExecutor()

Executors.newSingleThreadExecutor(); 

分享到:

滇ICP备2023006006号-16