java线程池的使用

import  java.util.concurrent.ExecutorService;
import  java.util.concurrent.Executors;
import  java.util.concurrent.ScheduledExecutorService;
import  java.util.concurrent.ScheduledFuture;
import  java.util.concurrent.TimeUnit;


/**/ /*
 * 学习使用JDK5以上的线程池操作
 
*/


public   class  ThreadPool  {

    
public static void main(String[] args)
    
{
            
/**//*
             * 可以安排线程运行时间
             * 
             
*/

        
            
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
            
final Runnable beeper = new Runnable() 
            
{     
                
int count = 0
                
public void run() 
                
{        
                    System.out.println( 
" beep " + (++count));
                    
                }
    
            }
;
            
final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate(beeper, 12,TimeUnit.SECONDS);
            
            scheduler.schedule(
new Runnable() 
                                
{      
                                    
public void run()
                                    
{        
                                        beeperHandle.cancel(
true);   
                                        scheduler.shutdown();
                                    }
    
                                }
200, TimeUnit.SECONDS
                                );
            
/**//*
             * 不可以安排线程的运行时间
             
*/

            ExecutorService    exec 
= Executors.newFixedThreadPool(2);    
            
for(int index = 0; index < 200; index++
            
{
                Runnable run 
= new Runnable()
                
{
                    
public void run() 
                    
{   long time =(long)(Math.random() * 1000);
                        System.out.println(
"Sleeping " + time + "ms");
                        
try 
                            Thread.sleep(time);
                            }
 catch (InterruptedException e)
                            
{           
                                
                            }
        
                    }

                }
;
                exec.execute(run);    
            }

            exec.shutdown();  
    
    }

    
    
}

你可能感兴趣的:(java线程池的使用)