池中有很多存在的线程
启动线程T1—-执行线程任务T2—-线程回收T3
单线程,可重复利用
package thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/*
* 线程池
*/
public class Thread_12 {
public static void main(String[] args) {
ExecutorService pool = Executors.newSingleThreadExecutor();//单线程,可重复利用
/*ExecutorService pool = Executors.newFixedThreadPool(3);//固定线程,可重复利用*/
MyTask task1 = new MyTask();
MyTask task2 = new MyTask();
MyTask task3 = new MyTask();
MyTask task4 = new MyTask();
MyTask task5 = new MyTask();
pool.execute(task1);
pool.execute(task2);
pool.execute(task3);
pool.execute(task4);
pool.execute(task5);
pool.shutdown();
}
}
固定线程,可重复利用
package thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/*
* 线程池
*/
public class Thread_12 {
public static void main(String[] args) {
/*ExecutorService pool = Executors.newSingleThreadExecutor();//单线程,可重复利用*/
ExecutorService pool = Executors.newFixedThreadPool(3);//固定线程,可重复利用
MyTask task1 = new MyTask();
MyTask task2 = new MyTask();
MyTask task3 = new MyTask();
MyTask task4 = new MyTask();
MyTask task5 = new MyTask();
pool.execute(task1);
pool.execute(task2);
pool.execute(task3);
pool.execute(task4);
pool.execute(task5);
pool.shutdown();
}
}
创建线程,可重复利用:
package thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/*
* 线程池
*/
public class Thread_12 {
public static void main(String[] args) {
/*ExecutorService pool = Executors.newSingleThreadExecutor();//单线程,可重复利用 */
/*ExecutorService pool = Executors.newFixedThreadPool(3);//固定线程,可重复利用*/
ExecutorService pool = Executors.newCachedThreadPool();//创建线程,可重复利用
MyTask task1 = new MyTask();
MyTask task2 = new MyTask();
MyTask task3 = new MyTask();
MyTask task4 = new MyTask();
MyTask task5 = new MyTask();
pool.execute(task1);
pool.execute(task2);
pool.execute(task3);
pool.execute(task4);
pool.execute(task5);
pool.shutdown();
}
}
调度
package thread;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Thread_13 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);
pool.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" "+"scheduleAtFixedRate");
}
}, 1000, 5000, TimeUnit.MICROSECONDS);//每隔5秒执行一次
pool.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" "+TimeUnit.MICROSECONDS);
}
}, 1000, 3000, TimeUnit.MICROSECONDS);//每隔3秒执行一次
}
}
请关注“知了堂学习社区”,地址:http://www.zhiliaotang.com/portal.php