java.util.concurrent.Executors详解
Class Executors APIFactory and utility methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes defined in this package. This class supports the following k
Factory and utility methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes defined in this package. This class supports the following kinds of methods:
-
Methods that create and return an ExecutorService set up with commonly useful configuration settings.
-
Methods that create and return a ScheduledExecutorService set up with commonly useful configuration settings.
-
Methods that create and return a “wrapped” ExecutorService, that disables reconfiguration by making implementation-specific methods inaccessible.
-
Methods that create and return a ThreadFactory that sets newly created threads to a known state.
-
Methods that create and return a Callable out of other closure-like forms, so they can be used in execution methods requiring Callable.
// 固定大小线程池
val threadPool: ExecutorService = Executors.newFixedThreadPool(5)
//单任务线程池
val singleThreadPool: ExecutorService = Executors.newSingleThreadExecutor()
//可变线程池
val cachedThreadPool: ExecutorService = Executors.newCachedThreadPool()
//延迟或者定时线程池
val scheduledThreadPool: ScheduledExecutorService = Executors.newScheduledThreadPool(5)
//单任务延迟或者定时线程池
val singleScheduled: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor()
类型
- 固定大小的线程池
Executors.newFixedThreadPool(5)
- 单任务线程池
Executors.newSingleThreadExecutor()
- 可变线程池
Executors.newCachedThreadPool()
- 单任务定时线程池
Executors.newSingleThreadScheduledExecutor()
- 定时线程池
Executors.newScheduledThreadPool(5)
import java.util.concurrent.{ExecutorService, Executors, ScheduledExecutorService, TimeUnit}
object Pool {
def main(args: Array[String]): Unit = {
// 固定大小线程池
val threadPool: ExecutorService = Executors.newFixedThreadPool(1)
//单任务线程池
val singleThreadPool: ExecutorService = Executors.newSingleThreadExecutor()
//可变线程池
val cachedThreadPool: ExecutorService = Executors.newCachedThreadPool()
//延迟或者定时线程池
val scheduledThreadPool: ScheduledExecutorService = Executors.newScheduledThreadPool(1)
//单任务延迟或者定时线程池
val singleScheduled: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor()
for (i <- 1 to 5) {
println(i)
threadPool.execute(new ThreadDemo("thread" + i))
}
for (i <- 20 to 25) {
println(i)
singleThreadPool.execute(new ThreadDemo("thread" + i))
}
for (i <- 25 to 30) {
println(i)
//延迟n秒执行
scheduledThreadPool.schedule(new ThreadDemo("thread" + i), 3, TimeUnit.SECONDS)
}
scheduledThreadPool.shutdown()
for (i <- 30 to 35) {
println(i)
//延迟1秒,每隔3秒执行
scheduledThreadPool.scheduleAtFixedRate(new ThreadDemo("thread" + i), 1,3, TimeUnit.SECONDS)
}
}
}
class ThreadDemo(threadName: String) extends Runnable {
override def run(): Unit = {
for (i <- 1 to 5) {
println(s"$threadName run $i")
Thread.sleep(10)
}
}
更多推荐
所有评论(0)