建立一个线程池,把要执行的任务丢到线程池中。
package traditional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadPoolTest {
public static void main(String[] args) {
//创建线程池
// ExecutorService threadPool = Executors.newFixedThreadPool(3);//固定线程池
// ExecutorService threadPool = Executors.newCachedThreadPool();//动态变化线程数的线程池
ExecutorService threadPool = Executors.newSingleThreadExecutor();//创建的线程池中只有一个线程,(一个线程死掉后就会立即创建一个线程,确保线程池中有一个线程)
//给线程池添加任务
for(int i = 0; i<10; i++){
final int task = i;
threadPool.execute(new Runnable(){
@Override
public void run() {
for(int j = 0 ; j<10 ; j++){
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " is loop of " + j+
" for task " + task);
}
}
});
}
System.out.println("all of 10 tasks have committed!");
// threadPool.shutdownNow();
//**********用线程池启动定时器:
/**
* 10s后执行的任务
*/
Executors.newScheduledThreadPool(3).schedule(
new Runnable(){
@Override
public void run() {
System.out.println("bombing!");
}
},
10,
TimeUnit.SECONDS
);
/**
* 程序开始6s后爆炸,然后每隔2s爆炸
*/
Executors.newScheduledThreadPool(3).scheduleAtFixedRate(
new Runnable(){
@Override
public void run() {
System.out.println("bombing");
}
},
6,
2,
TimeUnit.SECONDS);
}
}
建立一个线程池,把要执行的任务丢到线程池中。
package traditional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadPoolTest {
public static void main(String[] args) {
//创建线程池
// ExecutorService threadPool = Executors.newFixedThreadPool(3);//固定线程池
// ExecutorService threadPool = Executors.newCachedThreadPool();//动态变化线程数的线程池
ExecutorService threadPool = Executors.newSingleThreadExecutor();//创建的线程池中只有一个线程,(一个线程死掉后就会立即创建一个线程,确保线程池中有一个线程)
//给线程池添加任务
for(int i = 0; i<10; i++){
final int task = i;
threadPool.execute(new Runnable(){
@Override
public void run() {
for(int j = 0 ; j<10 ; j++){
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " is loop of " + j+
" for task " + task);
}
}
});
}
System.out.println("all of 10 tasks have committed!");
// threadPool.shutdownNow();
//**********用线程池启动定时器:
/**
* 10s后执行的任务
*/
Executors.newScheduledThreadPool(3).schedule(
new Runnable(){
@Override
public void run() {
System.out.println("bombing!");
}
},
10,
TimeUnit.SECONDS
);
/**
* 程序开始6s后爆炸,然后每隔2s爆炸
*/
Executors.newScheduledThreadPool(3).scheduleAtFixedRate(
new Runnable(){
@Override
public void run() {
System.out.println("bombing");
}
},
6,
2,
TimeUnit.SECONDS);
}
}