技术:java8+ThreadPool
运行环境:IDEA 15.2 + jdk8 + windows 7
demo功能:提供jdk8 线程池类的基本使用demo
ps: 线程池, 批量执行 可执行的任务的, 线程池可以自己管理线程的生老病死。NewScheduledThreadPool,NewSingleThreadExecutor,NewWorkStealingPool这三个类使用方式请看源代码
public class MyTask implements Runnable {
private int taskType;
private String taskName;
public MyTask(int taskType, String taskName) {
this.taskType = taskType;
this.taskName = taskName;
}
@Override
public void run() {
System.out.println("task is running at thread " + Thread.currentThread().getId() + ",task type=" + taskType + ",task name=" + taskName);
}
public int getTaskType() {
return taskType;
}
public void setTaskType(int taskType) {
this.taskType = taskType;
}
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class NewSingleThreadExecutorDemo {
static ExecutorService pool = Executors.newSingleThreadExecutor();
public static void test() {
pool.execute(new MyTask(1, "111"));
pool.execute(new MyTask(2, "222"));
pool.execute(new MyTask(3, "333"));
pool.execute(new MyTask(4, "444"));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
pool.shutdown();
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class NewFixedThreadPoolDemo {
static ExecutorService pool = Executors.newFixedThreadPool(10);
public static void test() {
pool.execute(new MyTask(1, "111"));
pool.execute(new MyTask(2, "222"));
pool.execute(new MyTask(3, "333"));
pool.execute(new MyTask(4, "444"));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
pool.shutdown();
}
}
//执行所有的任务, 都使用一个线程。执行结果是 所有的任务都用的统一个线程id执行
@Test
public void test1() {
NewSingleThreadExecutorDemo.test();
}
//使用指定数量的线程, 执行全部的任务。 不同的任务可能用到相同的线程id执行
@Test
public void test2() {
NewFixedThreadPoolDemo.test();
}
test1()
task is running at thread 12,task type=1,task name=111
task is running at thread 12,task type=2,task name=222
task is running at thread 12,task type=3,task name=333
task is running at thread 12,task type=4,task name=444
test2()
task is running at thread 15,task type=4,task name=444
task is running at thread 13,task type=2,task name=222
task is running at thread 14,task type=3,task name=333
task is running at thread 12,task type=1,task name=111
欢迎添加微信,互相学习↑↑↑ -_-
白老虎
programming is not only to solve problems, ways to think
grafana 级连 菜单 templating (variables) 配置
AI 机器人 抓取 微信 聊天中的 百度网盘 分享地址和密码
rocketmq 集群搭建 (2master + 2slave + 2namesrv)