黑马程序员_多线程(4) 并发库应用

                          ------- android培训java培训、期待与您交流! ----------

一.线程池

 固定线程池,动态线程池,单例线程池

 定时器线程池

eg:

package com.it;

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

public class ThreadPool {

	/*
	int a,b;
	protected ThreadPool(int a,int b){
		this.a = a;
		this.b = b;
	}
	protected ThreadPool(){
		this(super.a,super.b);
	}
	*/
	
	public static void main(String[] args) {
		// ExecutorService executors = Executors.newFixedThreadPool(3);
		//ExecutorService executors = Executors.newCachedThreadPool();
		 ExecutorService executors = Executors.newSingleThreadExecutor();
		for(int j=0;j<5;j++){
	    final int task = j;
	    synchronized(ThreadPool.class){		
		executors.execute(new Runnable(){

			@Override
			public void run() {
				synchronized(ThreadPool.class){
				for(int i=0;i<10;i++){
					System.out.println(Thread.currentThread().getState()+" ::: "+Thread.currentThread().getName()+" is looping of "+ i+" the task of "+task);
				}
				}	
			 }			
	    	});
	      }
	  }
	  System.out.println(executors.toString());
	  
	 // executors.shutdown();
	  executors.execute(new Runnable(){
           @Override 
           public void run(){
        	   System.out.println(Thread.currentThread().getName()+" the state of threadpool is shut down");
           }
	  });
	
	  System.out.println(executors.toString());
	  
	  Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new Runnable(){
		  
		  @Override
		  public void run(){
			  System.out.println("bomping");
		  }
		  
	  }, 10,2,TimeUnit.SECONDS);
	}
}

-------------------------------------------------------------------------------------------------------------------------------

callable 与 Future

eg:

package com.it;

import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

public class CallableAndFuture {

	//private static String result;
	
	private final ScheduledExecutorService schedule = Executors.newScheduledThreadPool(1);
	
	public void beepAnHour(){
		final Runnable beeper = new Runnable(){

			@Override
			public void run() {
				System.out.println(Thread.currentThread().getName()+"--beep--");
				
			}
			
		};
		final ScheduledFuture<?> schedulefuture = schedule.scheduleAtFixedRate(beeper, 10, 10, TimeUnit.SECONDS);
		schedule.schedule(new Runnable(){

			@Override
			public void run() {
				schedulefuture.cancel(true);
			}
			
		}, 60*60, TimeUnit.SECONDS);
	}
	
	public static void mains(String[] args){
		new CallableAndFuture().beepAnHour();
	}
	public static void main(String[] args) {
		/*
	 ExecutorService threadPool = Executors.newFixedThreadPool(10);
	 
	 ExecutorService taskThreadPool = Executors.newSingleThreadExecutor(new ThreadFactory() {
		
		@Override
		public Thread newThread(Runnable r) {
			r = new Runnable(){

				@Override
				public void run() {
					System.out.println("taskThreadPool "+Thread.currentThread().getName());					
				}
				
			};
			return new Thread(r);
		}
	});
	 
	ScheduledExecutorService schedleThreadPool = Executors.newScheduledThreadPool(10);
	schedleThreadPool.schedule(new Callable<String>() {

		@Override
		public String call() throws Exception {
			// TODO 自动生成的方法存根
			return "hello";
		}
		
	}, 10,TimeUnit.SECONDS);
	 //taskThreadPool.
	 
	 for(int i=0;i<20;i++){
	 final int task = i;
	 threadPool.execute(new Runnable(){

		@Override
		public void run() {
			System.out.println(Thread.currentThread().getName()+" the task of "+task);
			
		}
		 
	  });
	 }
	 
	        /*
			try {
		  result = threadPool.submit(new Callable<String>() {

					@Override
					public String call() throws Exception {
					    Thread.sleep(2000);
						return "hello";
					}
					 
				}).get();
			} catch (InterruptedException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			} catch (ExecutionException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
			
	 */
		/*
	 Future<String> future = threadPool.submit(new Runnable(){

		@Override
		public void run() {
			for(int i=1;i<10;i++){
				System.out.println(Thread.currentThread().getName()+" the looping of "+i);
			}
		}		 
	 },"hello");
	 
		 
	 System.out.println("等待结果");
	 try {
		System.out.println("返回结果:"+future.get());
	} catch (InterruptedException e) {
		// TODO 自动生成的 catch 块
		e.printStackTrace();
	} catch (ExecutionException e) {
		// TODO 自动生成的 catch 块
		e.printStackTrace();
	}
	
	 for(int i=0;i<2;i++){
	 final int task = i;
	 threadPool.execute(new Runnable(){

		@Override
		public void run() {
			for(int i=0;i<10;i++){
				System.out.println(Thread.currentThread().getName()+" the looping of "+i+" the task of "+task);
			}
			
		}	 
	  });
	 }
	 List<Runnable> list = threadPool.shutdownNow();
	 System.out.println(list.toString());
	 for(Runnable runnable : list)
	 runnable.run();
	 */
	 ExecutorService threadPoolDemo = Executors.newFixedThreadPool(10);
	 CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPoolDemo);
	 for(int i=1;i<=10;i++){
	 final int sequce = i;
	 completionService.submit(new Callable<Integer>() {

		@Override
		public Integer call() throws Exception {
			Thread.sleep(new Random().nextInt(5000));
			return sequce;
		}
	  });
	 }
	 for(int i=1;i<=10;i++){
		try {
			System.out.println(completionService.take().get());
		} catch (InterruptedException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	 }
	}
}



---------------------------------------------------------------------------------------------------------------------------------

线程读写锁

eg:

package com.it;

import java.util.Random;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockDemo {

	class QueueInsrc{
		private Object data;
		private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
		protected QueueInsrc(Object data){
			this.data = data;
		}
		public void get(){
			readWriteLock.readLock().lock();
			try{
				System.out.println(Thread.currentThread().getName()+" be ready to read data");
				Thread.sleep((long)Math.random()*1000);
				System.out.println("have readed to data "+this.data);
				}catch(InterruptedException e){
					System.err.println(e.toString());
				}
			finally{
				readWriteLock.readLock().unlock();
			}
		}
		public void put(Object data){
			readWriteLock.writeLock().lock();
			try{
				System.out.println(Thread.currentThread().getName()+" be ready to write data");
				Thread.sleep((long)Math.random()*1000);
				this.data = data;
				System.out.println("have writed to data "+this.data);
			}catch(InterruptedException e){
				System.err.println(e.toString());
			}
			finally{
				readWriteLock.writeLock().unlock();
			}
		}
	}
	public static void main(String[] args) {
        final ReadWriteLockDemo.QueueInsrc queue=new ReadWriteLockDemo().new QueueInsrc(10);
        for(int i=0;i<10;i++){
        new Thread("getThread"){
        	
        	@Override
        	public void run(){
               queue.get();   		
        	}
        }.start();
        
        new Thread(new Runnable(){
			@Override
			public void run() {
			  queue.put(new Random().nextInt(100));				
			}        	
        },"putThread").start();
	 }
	}
}

缓存代理

eg:

package com.it;

	import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantReadWriteLock;
	
	public class CacheItem {
	
		private static Map<String ,Object> cache = new HashMap<String ,Object>();
		private static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
		//class 
		public static Object getObject(String key,Object target){
			readWriteLock.readLock().lock();
			Object polixy = null;	
			try{
				polixy = cache.get(key);
				if(polixy==null){
					readWriteLock.readLock().unlock();	
					readWriteLock.writeLock().lock();
					try{
					if(polixy==null){
					  polixy = target;
					  cache.put(key, polixy);
					}	
				 }
				  finally{
					readWriteLock.writeLock().unlock();
				  }
			   }
				readWriteLock.readLock().lock();		
			}
			finally{
				readWriteLock.readLock().unlock();
			}	
		 return polixy;			
	  }
		
		public static void main(String[] args) {
		 final CountDownLatch latch = new CountDownLatch(10);
		  for(int i=0;i<10;i++){
			 final int count = i; 
			 new Thread(new Runnable(){
	
				@Override
				public void run() {
					 try {
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					}
					 System.out.println(Thread.currentThread().getName()+" ::: "+count+" ::: "+CacheItem.getObject(String.valueOf(count), new Random().nextInt(1000)));
					 latch.countDown();
				}
				 
			 }).start();  
			
		  }
		  try {
				latch.await();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		
		     
			 for(Map.Entry<String, Object>  itdemo : cache.entrySet()){
				 try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
				 System.out.println("key="+itdemo.getKey()+","+"value="+itdemo.getValue());
			 }
			 
		//	 System.out.println(cache.toString());
		
		 /*
		 
		   // 键值对集合视图  Key - Value  entrySet() 
	     Set<Map.Entry<String,Object>> set = cache.entrySet();
		 for(Iterator<Map.Entry<String,Object>> it = set.iterator();it.hasNext();){
			 System.out.println(it.next().getKey()+":::"+it.next().getValue());
		 }
		
		 // 键集合视图 key  返回也是Set  keySet()
		 Set<String> key = cache.keySet();
		 for(String k : key){
			 System.out.println(k+":::"+cache.get(k));
		 }
		 
		for(Iterator<String> ey = key.iterator();ey.hasNext();){
			String temp=ey.next();
			System.out.println(temp+" ::: "+cache.get(temp));
		}
		
		//值集合视图   
		Collection coll = cache.values();
		for(Object obj : coll){
			System.out.println(obj);
		}
		
		for(Iterator<Object> value = coll.iterator();value.hasNext();){
			System.out.println(value.next());
		}
		*/
	}	
}

------------------------------------------------------------------------------------------------------------------------------------

Condtion 实现

多个Condition 条件阻塞 ,相当于传统线程notify,wait 通信

阻塞队列的实例

eg:

package com.it;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ConditionDemo {
	private final Lock lock = new ReentrantLock(); 
	private final Condition isFull = lock.newCondition();
	private final Condition isEmtry = lock.newCondition();
	private String[] data = new String[10];
	private int len, getStr,putStr;
	private StringBuilder buff = new StringBuilder();
	public void putData(){
		lock.lock();
		System.out.println("正在填充数据...");
		try{
			while(putStr<=data.length){
				if(putStr==data.length){
					putStr = 0;
					break;
				}
			data[putStr] = String.valueOf(new Random().nextInt(100));
			System.out.println("data["+putStr+"]="+data[putStr]);
			++putStr;
			++len;
			}
	    if(len!=data.length){
	    	this.putData();
	    }
	    else{	
	    	System.out.println(Thread.currentThread().getName()+" 填充完毕...");
			putStr=buff.length();
			try{
				isFull.await();
			}catch(InterruptedException e){
				System.err.println(e.toString());
			}			 
		  }
	    isEmtry.signal();
	    }
	   finally{
			lock.unlock();
		}	
	}
	public void getData(){
		lock.lock();
		System.out.println("正在截获信息...");
		try{			
		 while(getStr<=data.length){
		 if(getStr==data.length){
			 getStr = 0;
			 break;
		 }
		 String info = data[getStr];
		 buff.append(info+",");
	     ++getStr;
		 --len;
		 }
		
		 if(len==0){
			    System.out.println(Thread.currentThread().getName()+"截获数据完毕...");
				System.out.println(buff.toString());
				try {
					isEmtry.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}			
		 }else{ 
			this.getData();		
		   }
		 isFull.signal();
		}finally{
			lock.unlock();
		}
	}
	public static void main(String[] args) {
	   final ConditionDemo condition = new ConditionDemo();
	//   final CountDownLatch latch = new CountDownLatch(1);
	 
	   for(int i=0;i<10;i++){
	   new Thread(new Runnable(){
		   
		  @Override
		  public void run(){
			condition.putData();
		//	latch.countDown();
		  }
	     }).start();
	   }
	   for(int i=0;i<100;i++){
	   new Thread(new Runnable(){
		   
			  @Override
			  public void run(){
				  try{
				  Thread.sleep((long)Math.random()*10000);
				  condition.getData();
				  }catch(InterruptedException e){
					  System.err.println(e.toString());
				  }
			  }
		   }).start();
	   }
	}
}


------- android培训java培训、期待与您交流! ----------





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值