ITeye博客

JDK 5 并发库

ericFang · 2010-09-16 09:43 · J2SE · 编程语言 · Markdown

场景:控制某个资源可被同时访问的个数,acquire()获取一个许可,如果没有就等待,而release()释放一个许可。比如在Windows下可以设置共享文件的最大客户端访问个数。


public class TestSemaphore {
	public static void main(String[] args) {
		// 线程池
		ExecutorService exec = Executors.newCachedThreadPool();
		// 只能5个线程同时访问
		final Semaphore semp = new Semaphore(5);
		// 模拟20个客户端访问
		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 (InterruptedException e) {
					}
				}
			};
			exec.execute(run);
		}
		// 退出线程池
		exec.shutdown();
	}
}


评论(5)

  1. #5 楼 · ericFang · 2010-09-16 10:42

    http://www.iteye.com/topic/109150

  2. #4 楼 · ericFang · 2010-09-16 09:56

    场景:长时间运行的应用需要定时运行任务, 完成一些诸如统计、优化等工作,比如在电信行业中处理用户话单时,需要每隔1分钟处理话单;网站每天凌晨统计用户访问量、用户数;公司每个月的10号计算工资并进行转帐等.

    public class TestScheduledThread {
    	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(new Date() + " beep " + (++count));
    			}
    		};
    		// 1秒钟后运行,并每隔2秒运行一次
    		final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate(beeper, 1, 2, SECONDS);
    		// 2秒钟后运行,并每次在上次任务运行完后等待5秒后重新运行
    		final ScheduledFuture<?> beeperHandle2 = scheduler.scheduleWithFixedDelay(beeper, 2, 5, SECONDS);
    		// 30秒后结束关闭任务,并且关闭Scheduler
    		scheduler.schedule(new Runnable() {
    			public void run() {
    				beeperHandle.cancel(true);
    				beeperHandle2.cancel(true);
    				scheduler.shutdown();
    			}
    		}, 30, SECONDS);
    	}
    }
    
  3. #3 楼 · ericFang · 2010-09-16 09:52

    场景:当倒数到0时触发事件,也就是开锁,其他人就可以进入了。在一些应用场合中,需要等待某个条件达到要求后才能做后面的事情;同时当线程都完成后也会触发事件,以便进行后面的操作。

    public class TestCountDownLatch {
    	public static void main(String[] args) throws InterruptedException {
    		// 开始的倒数锁
    		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();//一直等待倒数到0
    						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();
    		end.await();
    		System.out.println("Game Over");
    		exec.shutdown();
    	}
    }
    
  4. #2 楼 · ericFang · 2010-09-16 09:46

    场景:有时候在实际应用中,某些操作很耗时,但又不是不可或缺的步骤。比如用网页浏览器浏览新闻时,最重要的是要显示文字内容,至于与新闻相匹配的图片就没有那么重要的,所以此时首先保证文字信息先显示,而图片信息会后显示,但又不能不显示,由于下载图片是一个耗时的操作,所以必须一开始就得下载。

    public class TestFutureTask {
    	public static void main(String[] args)throws InterruptedException,
    			ExecutionException {
    		final ExecutorService exec = Executors.newFixedThreadPool(5);
    		Callable<String> call = new Callable<String>() {
    			public String call() throws Exception {
    				Thread.sleep(1000 * 5);
    				return "Other less important but longtime things.";
    			}
    		};
    		Future<String> task = exec.submit(call);
    		// 重要的事情
    		Thread.sleep(1000 * 3);
    		System.out.println("Let's do important things.");
    		// 其他不重要的事情
    		String obj = task.get();
    		System.out.println(obj);
    		// 关闭线程池
    		exec.shutdown();
    		System.out.println(Runtime.getRuntime().availableProcessors());
    	}
    }
    
  5. #1 楼 · ericFang · 2010-09-16 09:45

    场景:浏览网页时,浏览器了5个线程下载网页中的图片文件,由于图片大小、网站访问速度等诸多因素的影响,完成图片下载的时间就会有很大的不同。如果先下载完成的图片就会被先显示到界面上,反之,后下载的图片就后显示.

    public class TestCompletionService {
    	public static void main(String[] args) throws InterruptedException,ExecutionException {
    		ExecutorService exec = Executors.newFixedThreadPool(10);
    		CompletionService<String> serv = new ExecutorCompletionService<String>(exec);
    		for (int index = 0; index < 5; index++) {
    			final int NO = index;
    			Callable<String> downImg = new Callable<String>() {
    				public String call() throws Exception {
    					Thread.sleep((long) (Math.random() * 10000));
    					return "Downloaded Image " + NO;
    				}
    			};
    			serv.submit(downImg);
    		}
    		Thread.sleep(1000 * 2);
    		System.out.println("Show web content");
    		for (int index = 0; index < 5; index++) {
    			Future<String> task = serv.take();
    			String img = task.get();
    			System.out.println(img);
    		}
    		System.out.println("End");
    		// 关闭线程池
    		exec.shutdown();
    	}
    }
    

评论功能维护中,当前仅展示历史评论。