线程和线程池的使用

参考:http://www.cnblogs.com/dolphin0520/p/3932921.html

1、线程:循环新建10个线程

注意:final定义的变量才能在run()方法里使用 

package com.test;

public class TestThread {

	public static void main(String[] args) {
		for(int i =0; i <9; i++){
			//final变量才能传到run()方法里
			final int task = i;	
			new Thread(new Runnable(){	
				@Override
				public synchronized void run() {
					System.out.println("task:" + task);
				}
				
			}).start();
		}
		
	}
	
}

2、线程池

不提倡直接使用ThreadPoolExecutor,Java通过Executors提供四种线程池,分别为:


(1)newCachedThreadPool

  创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
(2)newFixedThreadPool

  创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
(3)newScheduledThreadPool

  创建一个定长线程池,支持定时及周期性任务执行。
(4)newSingleThreadExecutor

  创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

如下是newFixedThreadPool的使用实例:

package com.test;

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

public class TestExcutor {

	public static void main(String[] args) {
		//线程池接口:ExecutorService
		ExecutorService fixThreadPool = Executors.newFixedThreadPool(5);
		for(int i=1; i<=5; i++){
			final int task =i;
			fixThreadPool.execute(new Runnable(){

				@Override
				public synchronized void run() {
					for(int j=1; j<=3;j++){
						System.out.println(Thread.currentThread().getName() + "  " +"task:" + task + "   times:" +j);
					}
				}
				
			});
		}
		fixThreadPool.shutdown();
		
	}
	
}

  

原文地址:https://www.cnblogs.com/Donnnnnn/p/7676699.html