您的位置:首页 > 编程语言 > Java开发

Java线程池

2018-03-07 15:37 323 查看
线程池:就是把多个线程放在一起执行一个任务;
创建一个线程池:
代码package testDemo;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPool {

public static void main(String[] args) {
// TODO Auto-generated method stub
//创建一个线程池
ExecutorService exService = Executors.newCachedThreadPool();
for(int x = 0; x < 10; x++) {
int index = x;
exService.submit(() -> {
System.out.println(Thread.currentThread().getName()+ "、x = " + index);
});
}
exService.shutdown();//关闭线程池
}

}
创建单个线程的线程池:newSingleThreadExecutor()
package testDemo;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPool {

public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
//创建一个线程池
ExecutorService exService = Executors.newSingleThreadExecutor();
for(int x = 0; x < 10; x++) {
//Thread.sleep(200);
int index = x;
exService.submit(() -> {
System.out.println(Thread.currentThread().getName()+ "、x = " + index);
});
}
exService.shutdown();
}

}
创建固定大小的线程池:newFixedThreadExecutor();package testDemo;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPool {

public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
//创建一个线程池
ExecutorService exService = Executors.newFixedThreadPool(3);
for(int x = 0; x < 10; x++) {
//Thread.sleep(200);
int index = x;
exService.submit(() -> {
System.out.println(Thread.currentThread().getName()+ "、x = " + index);
});
}
exService.shutdown();
}

}
创建定时调度池:package testDemo;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ThreadPool {

public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
//创建一个具备有三个大小的定时调度线程池
ScheduledExecutorService exService = Executors.newScheduledThreadPool(1);
for(int x = 0; x < 10; x++) {
//Thread.sleep(200);
int index = x;
exService.scheduleAtFixedRate(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName()+ "、= " + index);
}
},3, 2, TimeUnit.SECONDS);//使用的是一个秒的单位,每三秒执行一次
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java线程池