Executors 类的 newSingleThreadExecutor() 方法创建一个 Executor,该 Executor 使用单个工作线程在无界队列上运行。 (但请注意,如果该单个线程在关闭前的执行过程中因失败而终止,则在需要执行后续任务时将替换为一个新线程。)。
用法
public static ExecutorService newSingleThreadExecutor()
public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory)
参数
threadFactory - 创建新线程时使用的工厂
返回
新创建的 single-threaded Executor
抛出
NullPointerException
例子1
//import statement
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ExecutorsnewSingleThreadExecutorExample1 {
public static void main(String[] args) {
System.out.println("current thread:" + Thread.currentThread().getName());
System.out.println(" Executor Service...");
ExecutorService ex = Executors.newSingleThreadExecutor();
System.out.println("Runnable...");
Runnable runnable = () -> {
System.out.println("::" + Thread.currentThread().getName());
};
System.out.println("Submit the task ");
ex.submit(runnable);
}
}
输出:
current thread:main Executor Service... Runnable... Submit the task ::pool-1-thread-1
例子1
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ExecutorsnewSingleThreadExecutorExample2 {
public static void main(final String[] arguments) throws InterruptedException {
ExecutorService ex = Executors.newSingleThreadExecutor();
try {
ex.submit(new myThread5());
System.out.println("Shutingdown executor");
ex.shutdown();
ex.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
System.err.println(e);
} finally {
if (!ex.isTerminated()) {
System.err.println("cancel tasks");
}
ex.shutdownNow();
System.out.println(" finished");
}
}
static class myThread5 implements Runnable {
public void run() {
try {
Long duration = (long) (Math.random() * 90);
System.out.println("Running Task!");
TimeUnit.SECONDS.sleep(duration);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
输出:
Shutingdown executor Running Task!
相关用法
- Java Executors newScheduledThreadPool()用法及代码示例
- Java Executors newCachedThreadPool()用法及代码示例
- Java Executors newFixedThreadPool()用法及代码示例
- Java Executors Callable()用法及代码示例
- Java Executors defaultThreadFactory()用法及代码示例
- Java Executor newWorkStealingPool()用法及代码示例
- Java Executor privilegedThreadFactory()用法及代码示例
- Java Enum equals()用法及代码示例
- Java EnumSet range()用法及代码示例
- Java EnumMap remove()用法及代码示例
- Java Enum toString()用法及代码示例
- Java EnumMap hashCode()用法及代码示例
- Java EnumMap get()用法及代码示例
- Java EnumSet complementOf()用法及代码示例
- Java Enum ordinal()用法及代码示例
- Java EnumSet clone()用法及代码示例
- Java EnumMap entrySet()用法及代码示例
- Java EnumMap containsKey()用法及代码示例
- Java EnumMap containsValue(value)用法及代码示例
- Java Enumeration asIterator()用法及代码示例
注:本文由纯净天空筛选整理自 Java Executors newSingleThreadExecutor() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。