使用线程池方法
java通过Executors提供四种线程池:分别为 newCachedThreadPool; newFixedThreadPool; newScheduledThreadPool; newSingleThreadExecutor
package
test;
优点:
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- public class ThreadPoolExecutorTest {
- public static void main(String[] args) {
- ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
- for (int i = 0; i < 10; i++) {
- final int index = i;
- fixedThreadPool.execute(new Runnable() {
- public void run() {
- try {
- System.out.println(index);
- Thread.sleep(2000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- });
- }
- }
- }
- }
定长线程池的大小最好根据系统资源进行设置。如Runtime.getRuntime().availableProcessors()
创建一个线程:
1、通过实现Runnable接口
执行一个方法:
public void run()
2、通过继承Thread类本身
Thread(Runnable threadOb,String threadName);
这里,threadOb 是一个实现Runnable 接口的类的实例,并且 threadName指定新线程的名字。
新线程创建之后,你调用它的start()方法它才会运行。
void start();