Chinaunix首页 | 论坛 | 博客
  • 博客访问: 703962
  • 博文数量: 147
  • 博客积分: 6010
  • 博客等级: 准将
  • 技术积分: 1725
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-22 10:36
文章分类

全部博文(147)

文章存档

2011年(1)

2010年(1)

2009年(35)

2008年(110)

我的朋友

分类: Java

2008-10-30 17:35:33

package test;
import java.util.concurrent.*;
public class TestSemaphore {
/*
 * 操作系统的信号量是个很重要的概念,在进程控制方面都有应用。Java并发库的Semaphore可以很轻松完成信号量控制,
 * Semaphore可以控制某个资源可被同时访问的个数,acquire()获取一个许可,如果没有就等待,
 * 而release()释放一个许可。比如在Windows下可以设置共享文件的最大客户端访问个数。
 *Semaphore维护了当前访问的个数,提供同步机制,控制同时访问的个数。在数据结构中链表可以保存“无限”的节点
 *用Semaphore可以实现有限大小的链表。另外重入锁ReentrantLock也可以实现该功能,但实现上要负责些,代码也要复杂些。
 *下面的Demo中申明了一个只有5个许可的Semaphore,而有20个线程要访问这个资源,通过acquire()和release()获取和释放访问许可。
 */
  
 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
//newCachedThreadPool 创建一个可根据需要创建新线程的线程池,但是在以前构造的线程可用时将重用它们。
ExecutorService exec=Executors.newCachedThreadPool();
//Semaphore一个计数信号量。
final Semaphore semp=new Semaphore(5);
for(int index=0;index<20;index++){
 final int NO=index;
 Runnable run=new Runnable(){
  public void run(){
   try{
    //从此信号量获取一个许可,在提供一个许可前一直将线程阻塞,否则线程被中断。
    semp.acquire();
    System.out.println("Accessing:"+NO);
    Thread.sleep((long)(Math.random()*10000));
    // 释放一个许可,将其返回给信号量。
    semp.release();
   }catch(Exception e){}
  }
 };
 //Future submit(Runnable|Callable)提交一个 Runnable 任务用于执行,并返回一个表示该任务的 Future。
 //void execute(Runnable)    在未来某个时间执行给定的命令。该命令可能在新的线程、已入池的线程或者正调用的线程中执行,
 //这由 Executor 实现决定。
 exec.execute(run);
}
exec.shutdown();
 }
}
package test;
import java.util.concurrent.*;
public class Test{
 public static void main(String args[]){
  /*
   * ExecutorService:一个线程池管理者,其实现类有多种,比如普通线程池,定时调度线程池ScheduledExecutorService等,
   * 我们能把一个Runnable,Callable提交到池中让其调度。
   */
  ExecutorService exec=Executors.newFixedThreadPool(2);
  for(int index=0;index<8;index++){
   //定义Runnable对象
   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){     
    }
    }
   };   
   //执行run对象
   //在未来某个时间执行给定的命令。该命令可能在新的线程、已入池的线程或者正调用的线程中执行,这由 Executor 实现决定。
   exec.execute(run);
  }
  //关闭线程池;shutdown()方法:启动一次顺序关闭,执行以前提交的任务,但不接受新任务
  exec.shutdown(); 
  /*
   * 上面是一个简单的例子,使用了2个大小的线程池来处理100个线程。但有一个问题:在for循环的过程中,
   * 会等待线程池有空闲的线程,所以主线程会阻塞的。为了解决这个问题,一般启动一个线程来做for循环,
   * 就是为了避免由于线程池满了造成主线程阻塞。不过在这里我没有这样处理。[重要修正:经过测试,
   * 即使线程池大小小于实际线程数大小,线程池也不会阻塞的,这与Tomcat的线程池不同,
   * 它将Runnable实例放到一个“无限”的BlockingQueue中,所以就不用一个线程启动for循环,Doug Lea果然厉害]
         *另外它使用了Executors的静态函数生成一个固定的线程池,顾名思义,线程池的线程是不会释放的,
         *即使它是Idle。这就会产生性能问题,比如如果线程池的大小为200,当全部使用完毕后,
         *所有的线程会继续留在池中,相应的内存和线程切换(while(true)+sleep循环)都会增加。
         *如果要避免这个问题,就必须直接使用ThreadPoolExecutor()来构造。可以像Tomcat的线程池一样设置“最大线程数”、
         *“最小线程数”和“空闲线程keepAlive的时间”。通过这些可以基本上替换Tomcat的线程池实现方案。
         *需要注意的是线程池必须使用shutdown来显式关闭,否则主线程就无法退出。shutdown也不会阻塞主线程。
   */
 }
}
 
 
package test;
import java.io.File;
import java.io.FileFilter;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class TestBlockingQueue {
 /*
  * 下面的例子比较简单,一个读线程,用于将要处理的文件对象添加到阻塞队列中,另外四个写线程用于取出文件对象,
  * 为了模拟写操作耗时长的特点,特让线程睡眠一段随机长度的时间。另外,该Demo也使用到了线程池和原子整型(AtomicInteger),
  * AtomicInteger可以在并发情况下达到原子化更新,避免使用了synchronized,而且性能非常高。
  * 由于阻塞队列的put和take操作会阻塞,为了使线程退出,特在队列中添加了一个“标识 ”,算法中也叫“哨兵”,
  * 当发现这个哨兵后,写线程就退出。
     * 当然线程池也要显式退出了
  */
 static long randomTime(){
  return (long)(Math.random()*1000);
 }
 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
// 能容纳100个文件
final BlockingQueue queue=new LinkedBlockingQueue(100);
//线程池
final ExecutorService exec=Executors.newFixedThreadPool(5);
final File root=new File("D:\\java");
//完成标志
final File exitFile=new File("");
//读的个数
//AtomicInteger可以用原子方式更新的 int 值
final AtomicInteger rc=new AtomicInteger();
//写的个数
final AtomicInteger wc=new AtomicInteger();
Runnable read=new Runnable(){
 public void run(){
  scanFile(root);
  scanFile(exitFile);
 }
 public void scanFile(File file){
 if(file.isDirectory()){
  File[] files=file.listFiles(new FileFilter(){
   public boolean accept(File pathname){
    return pathname.isDirectory()||pathname.getPath().endsWith(".java");
   }
  });
  for(File one:files)
   scanFile(one);
 }else{
  try{
   //以原子方式将当前值加 1。
   int index=rc.incrementAndGet();
   System.out.println("Read0:"+index+" "+file.getPath());
  //将指定的元素添加到队列的尾部,如有必要,则等待空间变得可用
   queue.put(file);
  }catch(InterruptedException e){}
 }
 }
};
exec.submit(read);
for(int index=0;index<4;index++){
 final int NO=index;
 Runnable write=new Runnable(){
  String threadname="write"+NO;
  public void run(){
   while(true){
    try{
     Thread.sleep(randomTime());
     int index=wc.incrementAndGet();
     //检索并移除此队列的头部,如果此队列不存在任何元素,则一直等待
     File file=(File)queue.take();
     if(file==exitFile){
      queue.put(exitFile);
      break;
     }
     System.out.println(threadname+":"+index+" "+file.getPath());
    }catch(InterruptedException e){}
   }
  }
 };
 exec.submit(write);
}
exec.shutdown();
 }
}
 
package test;
import java.util.concurrent.*;
public class TestCompletionService {
/*
 * 考虑以下场景:浏览网页时,浏览器5个线程下载网页中的图片文件,由于图片大小、网站访问速度等诸多因素的影响,
 * 完成图片下载的时间就会有很大的不同。如果先下载完成的图片就会被先显示到界面上,反之,后下载的图片就后显示。
 * Java的并发库的CompletionService可以满足这种场景要求。该接口有两个重要方法:submit()和take()。
 * submit用于提交一个runnable或者callable,一般会提交给一个线程池处理;而take就是取出已经执行完毕runnable或者
 * callable实例的Future对象,如果没有满足要求的,就等待了。
 * CompletionService还有一个对应的方法poll,该方法与take类似,只是不会等待,如果没有满足要求,就返回null对象。
 */
 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
ExecutorService exec=Executors.newFixedThreadPool(10);
/*CompletionService将生产新的异步任务与使用已完成任务的结果分离开来的服务。生产者 submit 执行的任务。
使用者 take 已完成的任务,并按照完成这些任务的顺序处理它们的结果。
*/
/*该构造函数 使用为执行基本任务而提供的执行程序创建一个 ExecutorCompletionService,
 *  并将 LinkedBlockingQueue 作为完成队列。
 */
CompletionService serv=new ExecutorCompletionService(exec);
for(int index=0;index<5;index++){
 final int NO=index;
 Callable downImg=new Callable(){
  public String call()throws Exception{
   Thread.sleep((long)(Math.random()*10000));
   return "downloaded Image"+NO;
  }
 };
 // 提交要执行的值返回任务,并返回表示挂起的任务结果的 Future。
 serv.submit(downImg);
}
try{
Thread.sleep(1000*2);
System.out.println("show web content");
for(int index=0;index<5;index++){
 //检索并移除表示下一个已完成任务的 Future,如果目前不存在这样的任务,则等
 Future task=serv.take();
 String img=(String)task.get();
 System.out.println(img);
}
System.out.println("end");
exec.shutdown();
}catch(Exception e){}
 }
}
 
 
 
package test;
import java.util.concurrent.*;
public class TestCountDownLatch {
/*
 * 一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
 *用给定的计数 初始化 CountDownLatch。由于调用了 countDown() 方法,所以在当前计数到达零之前,await
 *方法会一直受阻塞。之后,会释放所有等待的线程,await 的所有后续调用都将立即返回。这种现象只出现一次——计数无法被重置。
 *如果需要重置计数,请考虑使用 CyclicBarrier。
 *CountDownLatch 是一个通用同步工具,它有很多用途。将计数 1 初始化的 CountDownLatch 用作一个简单的开/关锁存器,
 *或入口:在通过调用 countDown() 的线程打开入口前,所有调用 await 的线程都一直在入口处等待。用 N 初始化的
 *CountDownLatch 可以使一个线程在 N 个线程完成某项操作之前一直等待,或者使其在某项操作完成 N 次之前一直等待。
 *CountDownLatch 的一个有用特性是,它不要求调用 countDown 方法的线程等到计数到达零时才继续,而在所有线程都能通过之前,
 *它只是阻止任何线程继续通过一个 await。
 */
 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  //构造一个用给定计数初始化的 CountDownLatch。
final CountDownLatch begin=new CountDownLatch(1);
final CountDownLatch end=new CountDownLatch(10);
final ExecutorService exec=Executors.newFixedThreadPool(10);
for(int index=0;index<10;index++){
 final int NO=index+1;
 Runnable run=new Runnable(){
  public void run(){
   try{
    //使当前线程在锁存器倒计数至零之前一直等待,除非线程被中断。
    begin.await();
    Thread.sleep((long)(Math.random()*10000));
    System.out.println("No."+NO+"arrived");
   }catch(InterruptedException e){
    
   }finally{
    //递减锁存器的计数,如果计数到达零,则释放所有等待的线程。
    end.countDown();
   }
  }
 };
 exec.submit(run);
}
System.out.println("Game Start");
begin.countDown();
try{
end.await();
}catch(Exception e){}
System.out.println("Game Over");
exec.shutdown();
 }
}

package test;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestCyclicBarrier {
 /**
  * @param args
  */
 /*在实际应用中,有时候需要多个线程同时工作以完成同一件事情,而且在完成过程中,
  * 往往会等待其他线程都完成某一阶段后再执行,等所有线程都到达某一个阶段后再统一执行。
     * 比如有几个旅行团需要途经深圳、广州、韶关、长沙最后到达武汉。旅行团中有自驾游的,有徒步的,
     *有乘坐旅游大巴的;这些旅行团同时出发,并且每到一个目的地,都要等待其他旅行团到达此地后再同时出发,直到都到达终点站武汉。
     *这时候CyclicBarrier就可以派上用场。CyclicBarrier最重要的属性就是参与者个数,另外最要方法是await()。
     *当所有线程都调用了await()后,就表示这些线程都可以继续执行,否则就会等待。
  */
 // 徒步需要的时间: Shenzhen, Guangzhou, Shaoguan, Changsha, Wuhan
private static int[] timeWalk={5,8,15,15,10};
//自驾游
private static int[] timeSelf={1,3,4,4,5};
//旅游大巴
private static int[] timeBus={2,4,6,6,7};
  static String now(){
  SimpleDateFormat sdf=new SimpleDateFormat("hh:mm:ss");
  return sdf.format(new Date())+":";
  }
  static class Tour implements Runnable{
   private int[] times;
   //CyclicBarrier是一个同步辅助类,它允许一组线程互相等待,直到到达某个公共屏障点
   private CyclicBarrier barrier;
   private String tourName;
   public Tour(CyclicBarrier barrier,String tourName,int[] times){
    this.times=times;
    this.barrier=barrier;
    this.tourName=tourName;
   }
   public void run(){
    try{
     Thread.sleep(times[0] * 1000);  
     System.out.println(now() + tourName + "Reached Shenzhen");  
     //在所有参与者都已经在此 barrier 上调用 await 方法之前,将一直等待
     barrier.await();  
     Thread.sleep(times[1] * 1000);  
     System.out.println(now() + tourName + "Reached Guangzhou");  
     barrier.await();  
     Thread.sleep(times[2] * 1000);  
     System.out.println(now() + tourName + "Reached Shaoguan");  
     barrier.await();  
     Thread.sleep(times[3] * 1000);  
     System.out.println(now() + tourName + "Reached Changsha");  
     barrier.await();  
     Thread.sleep(times[4] * 1000);  
     System.out.println(now() + tourName + "Reached Wuhan");  
     barrier.await(); 
    }catch(InterruptedException e){    
    }catch(BrokenBarrierException e){    
    }
   }
  }
 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  // 三个旅行团  
  CyclicBarrier barrier = new CyclicBarrier(3);  
  ExecutorService exec = Executors.newFixedThreadPool(3);
  // 提交一个 Runnable 任务用于执行,并返回一个表示该任务的 Future
  exec.submit(new Tour(barrier, "WalkTour", timeWalk));  
  exec.submit(new Tour(barrier, "SelfTour", timeSelf));  
  exec.submit(new Tour(barrier, "BusTour", timeBus));  
  exec.shutdown(); 
 }
}
 
 
package test;
import java.util.concurrent.*;
public class TestFutureTask {
/*
 * Future的使用方法:一个非常耗时的操作必须一开始启动,但又不能一直等待;
 * 其他重要的事情又必须做,等完成后,就可以做不重要的事情
 */
 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
final ExecutorService exec=Executors.newFixedThreadPool(5);
//Callable返回结果并且可能抛出异常的任务
Callable call=new Callable(){
 public String call()throws Exception{
  System.out.println("开始做不重要的事情");  
  Thread.sleep(1000*5);
  return "Other less important but longtime things";
 }
};
/*
 * Future 表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。
 * 计算完成后只能使用 get 方法来检索结果,如有必要,计算完成前可以阻塞此方法。取消则由 cancel 方法来执行。
 * 还提供了其他方法,以确定任务是正常完成还是被取消了。一旦计算完成,就不能再取消计算
 */
//submit提交一个返回值的任务用于执行,返回一个表示任务的未决结果的 Future。
Future task=exec.submit(call);
try{
 //// 重要的事情
 Thread.sleep(1000*3);
 System.out.println("Let's do important things");
 // 如有必要,等待计算完成,然后检索其结果。
 //// 其他不重要的事情
 String obj=(String)task.get();
 System.out.println(obj);
}catch(Exception e){} 
 exec.shutdown();
}
}

package test;
import java.util.Date;
import java.util.concurrent.*;
import static java.util.concurrent.TimeUnit.SECONDS;  
public class TestScheduledThread {
 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  /*ScheduledExecutorService接口
   * 许多长时间运行的应用有时候需要定时运行任务
   * 可安排在给定的延迟后运行或定期执行的命令
   */
  /*
   * Executors中所定义的 Executor、ExecutorService、ScheduledExecutorService、
   * ThreadFactory 和 Callable 类的工厂和实用方法。
   */
  
final ScheduledExecutorService scheduler=Executors.newScheduledThreadPool(2);
final Runnable beeper=new Runnable(){
 int count=0;
 public void run(){
 System.out.println(new Date()+"beep"+(++count)); 
 }
};
/*ScheduledFuture scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
*创建并执行一个在给定初始延迟后首次启用的定期操作,后续操作具有给定的周期;也就是将在 initialDelay 后开始执行,
*然后在 initialDelay+period 后执行,
*接着在 initialDelay + 2 * period 后执行,依此类推。
*/
//1秒钟后运行,并每隔2秒运行一次
final ScheduledFuture beeperHandle=scheduler.scheduleAtFixedRate(beeper,1,2,SECONDS);
/*ScheduledFuture scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)
 * 创建并执行一个在给定初始延迟后首次启用的定期操作,随后,在每一次执行终止和下一次执行开始之间都存在给定的延迟。
 */
// 2秒钟后运行,并每次在上次任务运行完后等待5秒后重新运行
final ScheduledFuture beeperHandle2=scheduler.scheduleWithFixedDelay(beeper,2,5,SECONDS);
/*ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit)
 *创建并执行在给定延迟后启用的一次性操作。
*/
//30秒后结束关闭任务,并且关闭Scheduler 
//为了退出进程,上面的代码中加入了关闭Scheduler的操作。而对于24小时运行的应用而言,是没有必要关闭Scheduler的。
scheduler.schedule(new Runnable(){
 public void run(){
  beeperHandle.cancel(true);
  beeperHandle2.cancel(true);
  scheduler.shutdown();
 }
 
},30,SECONDS);
 }
}
阅读(1735) | 评论(0) | 转发(0) |
0

上一篇:系统服务守护程序

下一篇:内部类

给主人留下些什么吧!~~