newplan

阿基米德在洗澡時發現浮力原理,高興得來不及穿㆖褲子,跑到街㆖大喊:Eureka(我找到了)。
posts - 39, comments - 26, trackbacks - 0, articles - 4
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

java线程池的使用

Posted on 2008-12-13 19:04 山泉弯延 阅读(669) 评论(0)  编辑 收藏 引用
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();  
    
    }

    
    
}

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理