线程池
线程池的作用是重复利用线程,避免创建过多的线程。
创建线程池的类为ThreadPoolExecutor,但创建过程比较复杂,我们可以使用java自带的根据程序员使用频率较高的常用设置预设的线程池类创建。
线程池类:ExecutorServise
同步锁:Lock
控制线程数:Semaphore
ExecutorServise
方法
- ExecutorService threadpool = Executors.newFixedThreadPool(n); //创建n个线程的线程池
- newCacheThreadPool()
根据创建次数增加线程数,线程数达到最大值后
ExecutorService threadpool = Executors.newFixedThreadPool(3);
threadpool.execute( new Runnable() {
public void run()
{
...
}
}
//Future Callable可以得到线程的返回值
ExecutorService threadpool = Executors.newSingleThreadExecutor();
Future<String> future = threadpool.submit(new Callable<String>() {
public String call() {
return "hello, world";
}
});
Lock
在前面说过,同步锁Lock是
Lock lock = new ReentrantLock(); //锁
Condition con = lock.newCondition(); //控制wait和notify的类
con.await(); // = wait()
con.signal(); // = notify()
Semaphore
在线程池中,每个线程比喻成一盏灯,当创建线程时调用acquere()函数点一盏灯,结束时调用release()交出灯,灯的总数就是线程池中最大运行线程数。
Constructor:
Semphore sp = new Semaphore(n); // 总共n盏灯