黑马程序员-JDK1.5新特性之多线程并发库

  ------------- android培训java培训、java学习型技术博客、期待与您交流! ------------

        看java.util.concurrent
包及子包的 API 帮助文档 了解 java.util.concurrent.atomic 包, 查看 atomic 包文档页下面的介绍, 通过如下两个方法快速理解 atomic 包的意义:
        AtomicInteger 类的 boolean compareAndSet(expectedValue, updateValue);
        AtomicIntegerArray 类的 int addAndGet (int i, int delta);
        顺带解释 volatile 类型的作用,需要查看 java 语言规范。
l         了解 java.util.concurrent.lock

         线程池
         线程池的概念与Executors类的应用
        创建固定大小的线程池; 创建缓存线程池; 创建单一线程池
l         关闭线程池
        shutdown shutdownNow 的比较
l         用线程池启动定时器
        调用ScheduledExecutorService的schedule方法,返回的ScheduleFuture对象可以取消任务。
        支持间隔重复任务的定时方式,不直接支持绝对定时方式,需要转换成相对时间方式。 
        
package  cn. itcast. heima2;
import  java. util. concurrent. ExecutorService;
import  java. util. concurrent. Executors;
import  java. util. concurrent. TimeUnit;
public  class  ThreadPoolTest {
     /**
     *  @param  args
     */
     public  static  void  main( String[]  args) {
        
         //ExecutorService threadPool = Executors.newFixedThreadPool(3); //线3线
        
         //ExecutorService threadPool = Executors.newCachedThreadPool(); //,线
        
         ExecutorService  threadPool  =  Executors. newSingleThreadExecutor();  //线,线使线
        
         //线,线线线
        
         for( int  i = 1; i <= 10; i ++){
             
              final  int  task  =  i;
             
              threadPool. execute( new  Runnable(){
                  
                  @ Override
                  
                   public  void  run() {
                       
                        for( int  j = 1; j <= 10; j ++){
                            
                             try {
                                 
                                  Thread. sleep( 20);
                                 
                            }  catch ( InterruptedException  e) {
                                 
                                  e. printStackTrace();
                            }
                            
                             System. out. println( Thread. currentThread(). getName()  + 
                            
                             " is looping of "  +  j  +  " for  task of "  +  task);
                       }
                  }
             });
        }
        
         System. out. println( "all of 10 tasks have committed! ");
        
         //threadPool.shutdownNow(); //线
        
         //threadPool.shutdownNow();//线,3线,10,
        
         //3,.7
        
        
         Executors. newScheduledThreadPool( 3). scheduleAtFixedRate(
             
                   new  Runnable(){
                       
                       @ Override
                       
                   public  void  run() {
                       
                        System. out. println( "bombing!");
                  }},
                  
                   6,
                  
                   2,
                  
                   TimeUnit. SECONDS);
    }
}
  callable 与 Future
 
public  class  CallableAndFuture {
     /**
     *  @param  args
     */
     public  static  void  main( String[]  args) {
        
         ExecutorService  threadPool  =   Executors. newSingleThreadExecutor();
        
         Future < String >  future  =
        
              threadPool. submit(
                  
                   new  Callable < String >()
                  {
                        public  String  call()  throws  Exception {
                            
                             Thread. sleep( 2000);
                            
                             return  "hello";
                       };
                  }
        );
        
         System. out. println( "");
        
         try {
             
              System. out. println( ""  +  future. get());
             
        }  catch ( InterruptedException  e) {
             
              e. printStackTrace();
             
        }  catch ( Exception  e) {
              e. printStackTrace();
        }
        
         ExecutorService  threadPool2  =   Executors. newFixedThreadPool( 10);
        
         CompletionService < Integer >  completionService  =  
        
         new  ExecutorCompletionService < Integer >( threadPool2);  //Callable,
        
         //
        
         for( int  i = 1; i <= 10; i ++){
             
              final  int  seq  =  i;
             
              completionService. submit( new  Callable < Integer >() {
                  
                  @ Override
                  
                   public  Integer  call()  throws  Exception {
                       
                        Thread. sleep( new  Random(). nextInt( 5000));
                       
                        return  seq;
                  }
             });
        }
        
         for( int  i = 0; i < 10; i ++){
             
              try {
                  
                   System. out. printlncompletionService. take(). get());
                  
             }  catch ( InterruptedException  e) {
             
                   e. printStackTrace();
                  
             }  catch ( ExecutionException  e) {
             
                   e. printStackTrace();
             }
        }
    }
    
}

读写锁
public  class  ReadWriteLockTest {
    
     public  static  void  main( String[]  args) {
        
         final  Queue3  q3  =  new  Queue3();
        
         for( int  i = 0; i < 3; i ++)
        {
             
              new  Thread(){
                  
                   public  void  run(){
                       
                        while( true){
                            
                             q3. get();
                            
                       }
                  }
                  
             }. start();
              new  Thread(){
                  
                   public  void  run(){
                       
                        while( true){
                            
                             q3. put( new  Random(). nextInt( 10000));
                       }
                  }           
                  
             }. start();
        }
        
    }
}
class  Queue3{
    
     private  Object  data  =  null; //线线
    
     ReadWriteLock  rwl  =  new  ReentrantReadWriteLock();
    
     public  void  get(){
        
         rwl. readLock(). lock();
        
         try {
             
              System. out. println( Thread. currentThread(). getName()  +  " be ready to read data!");
             
              Thread. sleep(( long)( Math. random() * 1000));
             
              System. out. println( Thread. currentThread(). getName()  +  "have read data :"  +  data);
             
        }  catch ( InterruptedException  e) {
             
              e. printStackTrace();
             
        } finally{
             
              rwl. readLock(). unlock();
             
        }
    }
    
     public  void  put( Object  data){
         rwl. 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( Thread. currentThread(). getName()  +  " have write data: "  +  data); 
             
        }  catch ( InterruptedException  e) {
             
              e. printStackTrace();
             
        } finally{
             
              rwl. writeLock(). unlock();
             
        }
        
    }
}
 
Condition   //类似于传统线程里的wait 与 notify,基于Lock下使用,通常用来做同步互斥
 
public  class  ConditionCommunication {
     public  static  void  main( String[]  args) {
        
         final  Business  business  =  new  Business();
        
         new  Thread(
             
                   new  Runnable() {
                       
                       @ Override
                       
                        public  void  run() {
                       
                             for( int  i = 1; i <= 50; i ++){
                                 
                                  business. sub( i);
                            }
                            
                       }
                  }
                  
        ). start();
        
         for( int  i = 1; i <= 50; i ++){
             
              business. main( i);
        }
        
    }
     static  class  Business {
        
              Lock  lock  =  new  ReentrantLock();
             
              Condition  condition  =  lock. newCondition();
             
           private  boolean  bShouldSub  =  true;
           
           public   void  sub( int  i){
                
                lock. lock();
                
                try{
                     
                     while( ! bShouldSub){
                          
                          try {
                               
                             condition. await();
                            
                       }  catch ( Exception  e) {
                            
                             e. printStackTrace();
                       }
                       
                    }
                     
                        for( int  j = 1; j <= 10; j ++){
                            
                             System. out. println( "sub thread sequence of "  +  j  +  ",loop of "  +  i);
                            
                       }
                       
                     bShouldSub  =  false;
                     
                     condition. signal();
                     
               } finally{
                     
                     lock. unlock();
               }
          }
          
           public   void  main( int  i){
                
                lock. lock();
                
                try{
                     
                    while( bShouldSub){
                         
                           try {
                                    
                                  condition. await();
                                 
                            }  catch ( Exception  e) {
                            
                                  e. printStackTrace();
                            }
                      }
                          
                        for( int  j = 1; j <= 100; j ++){
                            
                             System. out. println( "main thread sequence of "  +  j  +  ",loop of "  +  i);
                       }
                       
                        bShouldSub  =  true;
                       
                        condition. signal();
                       
          } finally{
                
                lock. unlock();
                
          }
      }
    
    }
}
 

------------- android培训java培训、java学习型技术博客、期待与您交流! ------------

详情请查看:http://edu.csdn.net/


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值