线程和线程池的使用

参考: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();
		
	}
	
}

  

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值