package cm.pool;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class test {
public static Integer num = 20;
public static Integer i = 0;
public static void main(String[] args) {
/**
* 四种jdk中多线程的创建
*/
/*
* Executors.newSingleThreadExecutor().shutdown();
* Executors.newCachedThreadPool();
* Executors.newScheduledThreadPool(1);
* Executors.newFixedThreadPool(2);
*/
final CountDownLatch countDownLatch = new CountDownLatch(2);
// java内置线程池
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.submit(new Runnable() {
@Override
public synchronized void run() {
while (test.num > 0) {
test.num--;
test.i++;
System.out.println(Thread.currentThread().getName() + ":" + test.num);
}
countDownLatch.countDown();
}
});
executorService.submit(new Runnable() {
@Override
public synchronized void run() {
while (test.num > 0) {
test.num--;
test.i++;
System.out.println(Thread.currentThread().getName() + ":" + test.num);
}
countDownLatch.countDown();
}
});
executorService.submit(new Runnable() {
@Override
public void run() {
try {
countDownLatch.await();
System.out.println("统计线程1和线程2的执行次数:" + test.i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
executorService.shutdown();
Temp temp = new Temp();
final ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(10);
/**
* temp:线程任务
* 5:初始化时间
* 1:5秒后每1秒执行一次线程任务 TimeUnit.SECONDS:单位
*/
ScheduledFuture<?> scFuture = scheduled.scheduleWithFixedDelay(/**temp*/new Runnable() {
int r=0;
@Override
public synchronized void run() {
if(r==10){
scheduled.shutdown();
}else{
r++;
System.out.println("10个线程计数:"+Thread.currentThread().getName()+":"+r);
}
}
}, 5, 1, TimeUnit.SECONDS);
}
}
运行结果如下:
pool-1-thread-1:19
pool-1-thread-1:18
pool-1-thread-1:17
pool-1-thread-1:16
pool-1-thread-1:15
pool-1-thread-1:14
pool-1-thread-1:13
pool-1-thread-1:12
pool-1-thread-1:11
pool-1-thread-1:10
pool-1-thread-1:9
pool-1-thread-1:7
pool-1-thread-1:6
pool-1-thread-1:5
pool-1-thread-1:4
pool-1-thread-1:3
pool-1-thread-1:2
pool-1-thread-1:1
pool-1-thread-1:0
pool-1-thread-2:6
统计线程1和线程2的执行次数:20
10个线程计数:pool-2-thread-1:1
10个线程计数:pool-2-thread-1:2
10个线程计数:pool-2-thread-2:3
10个线程计数:pool-2-thread-1:4
10个线程计数:pool-2-thread-3:5
10个线程计数:pool-2-thread-2:6
10个线程计数:pool-2-thread-4:7
10个线程计数:pool-2-thread-1:8
10个线程计数:pool-2-thread-5:9
10个线程计数:pool-2-thread-3:10
1.newFixedThreadPool的使用。
2.开启了两个线程池pool1、pool2
3.通过countDownLatch保证递减结果完成之后输出。
4.newScheduledThreadPool的使用