死锁
- 各个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行。而导致俩个或多个线程都在等待对方释放资源,都停止执行的情况
- 最常见的 一个线程拿到了筷子在等待事务,另一个线程拿到了食物在等待筷子。俩个人都不释放,则造成死锁
- 不要在synchronized里面用synchronized 这样容易造成死锁。
产生死锁的四个条件
- 互斥条件 一个资源只能被一个线程占有
- 请求和保持条件 一个进程因请求资源而阻塞时,对已获得的资源保持不放
- 不剥夺条件 进程未获得的资源在未使用完之前,不能被强行剥夺
- 循环等待条件 若干进程之间形成一种头尾相接的循环等待资源关系
线程池
- 经常创建和销毁使用量特别大的资源,对性能影响大
- 提前创建好多个线程,放入线程池中,使用时直接获取,不使用时放回池子中。
- 好处:提高响应速度,降低资源消耗,便于线程管理
ExecutorService
- 真正的线程池接口,常见子类ThreadPoolExecutors
void execute(Runnable command):执行任务/命名,没有返回值,一般用来执行Runnable
Future submit(Callable task): 执行任务,有返回值,一般又来执行Callable
void shutdown(): 关闭线程池
Executors
- 工具类,线程池的工厂类,用来创建并返回不同类型的线程池
void testPoll(){
ExecutorService service= Executors.newFixedThreadPool(10);
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.shutdown();
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}