多线程(12)线程池

一:多线程

当线程处于就绪状态的时候(new Thread().start();),不能立马执行(立马执行run()方法),而是要等待cpu的调度,所以我们所写得多线程不是我们所能控制的。

a>.currentThread():静态方法获取当前线程对象  :   Thread.currentThread().getName();

b>.getPriority() :获取线程优先级;

一:运行状态的三个去向:

①进入到阻塞状态

②进入到终止状态

③进入到就绪状态:就是用yield 后进入到就绪状态

二:创建,就绪,运行,阻塞,终止

创建(new Thread ) , 就绪(new Thread.start()),运行(执行run方法),终止

当我们执行new Thread.start() 的方法时候,进入到就绪状态, 这个时候需要等待cpu随机调度, 

当我们执行run方法的时候, 执行sleep,或者wait方法,线程进入到阻塞状态

当我们再次通过notify 或者notifyall唤醒后,线程再次进入到就绪状态,等待cpu的随机调度。

一:使用线程池

①背景:经常创建和销毁,使用量特别大的资源,比如并发情况下的线程,对性能影响很大。

②思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。

③好处:提高响应速度(减少了创建新线程的时间);降低资源消耗(重复利用线程池中线程,不需要每次都创建);便于管理线程

④jdk5.0起提供了线程池相关API:ExecutorService和Executors

    A:ExecutorService:真正的线程池接口。常见子类ThreadPoolExecutor

         void   execute(Runnable command):执行任务,没有返回值,一般用来执行Runnable

         Future submit(Callable  task):执行任务,有返回值,一般又来执行Callable

        void  shutdown():关闭连接池

   B:Executors :工具类,线程池的工厂类,用于创建并返回不同类型的线程池。

public class Tread11 {
	public static void main(String[] args) {
		//创建服务,创建线程池
		//newFixedThreadPool  桉树为线程池大小
		ExecutorService executorService= Executors.newFixedThreadPool(10);
		//执行
		executorService.execute(new MyThread());
		executorService.execute(new MyThread());
		executorService.execute(new MyThread());
		//关闭
		executorService.shutdown();
	}
}
class MyThread implements Runnable{
	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName());
	}
}

pool-1-thread-2
pool-1-thread-1
pool-1-thread-3

 

posted @ 2021-05-03 13:45  iLisa  阅读(71)  评论(0)    收藏  举报