【黑马程序员】Java基础加强19:JDK1.5线程池与Lock机制

---------------------- ASP.Net+Android+IOS开发.Net培训、期待与您交流! ----------------------


一、线程池ThreadPool

1、线程池:

在多线程的处理过程中,首先创建一些线程将它们集合起来,当服务器接收到一个任务后,就从线程集合中取出一个空闲的线程为之服务,服务完后不关闭该线程,而是将该线程返回到线程集合中执行其它任务,如果有多个任务则由多个线程处理,线程不够任务排列等候,这个线程集合称之为线程池。

		//创建固定线程池,里面有三个线程
		//ExecutorService threadPool = Executors.newFixedThreadPool(3);
		
		//创建单一线程池,线程消亡后,再创建新的单一线程替换
		//ExecutorService threadPool = Executors.newSingleThreadExecutor();
		
		//创建缓存线程池,若有多个任务,就会创建多少个线程
		ExecutorService threadPool = Executors.newCachedThreadPool();
		for(int i=1; i<=10; i++){
			final int task = i;
			threadPool.execute(new Runnable(){
				public void run() {
					for(int j=1; j<=10; j++){
						System.out.println(Thread.currentThread().getName()
									+" is loop of "+j+" task of "+task);
					}
				}
			});
		}
		System.out.println("all of 10 tasks have commited!");
		//执行完所有任务后关闭线程池
		//threadPool.shutdown();
		//当前线程执行完后关闭,不管后续是否还有任务
		threadPool.shutdownNow();

2、调度线程池:

也就是定时器的概念,支持间隔重复任务的定时方式,不直接支持绝对定时方式,需要转换成相对时间方式。

		/*创建不重复任务的定时器,可以指定一个线程,
		若指定3个线程,则视为3个线程抢一个任务,谁抢到谁执行*/
		Executors.newScheduledThreadPool(3).schedule(
				new Runnable(){
					@Override
					public void run() {
						System.out.println("bombing!");					
					}
				},
				5,//5秒以后炸
				TimeUnit.SECONDS);//参数的时间单位秒
		
		//创建固定频率任务的定时器
		Executors.newScheduledThreadPool(3).scheduleAtFixedRate(
				new Runnable(){
					@Override
					public void run() {
						System.out.println("bombing!");					
					}
				},
				5,//5秒以后执行
				2,//以后再每隔2秒执行一次
				TimeUnit.SECONDS);

二、线程锁Lock

1Lock比传统线程模型中的synchronized方式更加面向对象,与生活中的锁类似,锁本身也应该是一个对象。两个线程执行的代码要实现同步互斥的效果,必须用同一个Lock对象。LockCondition可实现阻塞队列,具体如下所示:

//Lock与Condition的例子:实现三个线程交替运行的效果
package blog.itheima;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ThreeConditionCommunication {

	public static void main(String[] args) {
		//创建三个线程的共享数据business
		final Business business = new Business();
		
		//启动第二个线程,外循环运行10次
		new Thread(new Runnable() {
			public void run() {
				for(int i=1; i<=10; i++){
					business.sub2(i);
				}
			}
		}).start();
		
		//启动第三个线程,外循环运行10次
		new Thread(new Runnable() {
			public void run() {
				for(int i=1; i<=10; i++){
					business.sub3(i);
				}
			}
		}).start();
		
		//主线程,外循环运行10次
		for(int i=1; i<=10; i++){
			business.main(i);
		}
		/*如果外循环不一样,会发生死锁的情况,因为如果某个循环完成,
		等到更改为其对应标记时,其它二个循环都会处于等待情况*/
	}
	
	static class Business{
		//三个线程共享数据,需要使用同一把锁
		Lock lock = new ReentrantLock();
		//三个线程需要三个Condition的等待唤醒机制
		Condition condition1 = lock.newCondition();
		Condition condition2 = lock.newCondition();
		Condition condition3 = lock.newCondition();
		
		private int flag = 1;
		//初始标记为1,主线程执行
		public void main(int i){
			lock.lock();
			try{
				//用while会返回去二次判断条件,比if判断一次更健壮
				while(flag!=1){
					try {
						//标记若不为1,主线程等待
						condition1.await();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				//标记如果为1,执行循环
				for(int j=1; j<=50; j++){
					System.out.println(Thread.currentThread().getName()
							+"...执行次数:"+j+"...第"+i+"次循环");	
				}
				//循环完后,更改标记为2,并唤醒condition2
				flag = 2;
				condition2.signal();
			}finally{
				lock.unlock();
			}
		}
		public void sub2(int i){
			lock.lock();	
			try{
				//标记若不为2,子线程2等待
				while(flag!=2){
					try {
						condition2.await();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				for(int j=1; j<=20; j++){
					System.out.println(Thread.currentThread().getName()
							+"...执行次数:"+j+"...第"+i+"次循环");	
				}
				//循环完后,更改标记为3,并唤醒condition3
				flag = 3;
				condition3.signal();
			}finally{
				lock.unlock();
			}
		}
		
		public void sub3(int i){
			lock.lock();	
			try{
				//标记若不为3,子线程3等待
				while(flag!=3){
					try {
						condition3.await();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				for(int j=1; j<=30; j++){
					System.out.println(Thread.currentThread().getName()
							+"...执行次数:"+j+"...第"+i+"次循环");	
				}
				//循环完后,更改标记为1,并唤醒condition1
				flag = 1;
				condition1.signal();
			}finally{
				lock.unlock();
			}
		}
	}
}

2ReadWriterLock读写锁:分为读锁和写锁,多个读锁不互斥,读锁与写锁互斥,写锁与写锁互斥,这是由jvm自己控制的。若代码只读取数据,可多线程同时读,但不能同时写,那就上读锁;若代码要修改数据,只能有一个线程写,且不能同时读取,那就上写锁。用读写锁写设计一个缓冲系统,如下所示:

//设计一个缓存系统-->多个缓存代理的方式
package blog.itheima;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class CacheDemo {
	private static Map<String,Object> cache = 
							new HashMap<String,Object>();
	public static void main(String[] args) {
		getData("key");
	}
	
	private static Object getData(String key){
		ReadWriteLock rwl = new ReentrantReadWriteLock();
		//先读取数据,上读锁,可能有多个线程读取
		rwl.readLock().lock();
		Object value = null;
		try{
			value = cache.get(key);
			//如果key对应的值为null
			if(value==null){
				//释放读锁,上写锁
				rwl.readLock().unlock();
				rwl.writeLock().lock();
				try{
					//再次判断,防止上一个线程已经写入了数据
					if(value==null){
						//如果是第一个进入的线程,写入数据
						value="aaaa";
					}
				}finally{
					//数据写完,必须要释放写锁,放入finally中
					rwl.writeLock().unlock();
				}
				//其它线程进入,上读锁
				rwl.readLock().lock();
			}
		}finally{
			//读完之后必须释放读锁
			rwl.readLock().unlock();
		}
		return value;
	}
}

三、线程池的实例应用

调用线程池,利用ThreadLocal实现线程范围的多个变量的共享

//用ThreadLocal来实现线程范围的多个变量的共享
package blog.itheima;

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

public class ThreadPoolLocal {

	public static void main(String[] args) {
		ExecutorService threadPool = Executors.newCachedThreadPool();
		for(int i=0; i<3; i++){
			threadPool.execute(new Runnable(){
				public void run() {
					//随机取得一个整数
					int data = new Random().nextInt();
					System.out.println(Thread.currentThread().getName()
							+" has put Data: "+data);
					
					MyThreadScope.getThreadInstance().setName("name"+data);
					MyThreadScope.getThreadInstance().setAge(data);
					
					new A().get();
					new B().get();
				}
			});
		}
	}

	static class A{
		public void get(){
			MyThreadScope myData = MyThreadScope.getThreadInstance();
			System.out.println("A gets Data fron "
			+Thread.currentThread().getName()
					+": "+myData.getName()+"   data: "+myData.getAge());
		}
	}
	
	static class B{
		public void get(){
			MyThreadScope myData = MyThreadScope.getThreadInstance();
			System.out.println("B gets Data fron "
			+Thread.currentThread().getName()
					+": "+myData.getName()+"   data: "+myData.getAge());
		}
	}
}

class MyThreadScope{
	//当有几个变量共享线程内的数据时,可以模仿单例的形式,私有化本类,不让new对象
	private MyThreadScope(){}
	private static ThreadLocal<MyThreadScope> map = 
			new ThreadLocal<MyThreadScope>();
	public static MyThreadScope getThreadInstance(){
		MyThreadScope instance = map.get();
		//get() 返回此线程局部变量的当前线程副本中的值
		if(instance==null){
			instance = new MyThreadScope();
			map.set(instance);
		}
		return instance;
	}
	
	private String name;
	private int age;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}
---------------------- ASP.Net+Android+IOS开发.Net培训、期待与您交流! ----------------------
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值