我们都知道,在JDK1.5之前,Java中要进行业务并发时,通常需要有程序员独立完成代码实现,当然也有一些开源的框架提供了这些功能,但是这些依然没有JDK自带的功能使用起来方便。而当针对高质量Java多线程并发程序设计时,为防止死锁等现象的出现,比如使用java之前的wait()、notify()和synchronized等,每每需要考虑性能、死锁、公平性、资源管理以及如何避免线程安全性方面带来的危害等诸多因素,往往会采用一些较为复杂的安全策略,加重了程序员的开发负担.万幸的是,在JDK1.5出现之后,Sun大神(Doug Lea)终于为我们这些可怜的小程序员推出了java.util.concurrent工具包以简化并发完成。开发者们借助于此,将有效的减少竞争条件(race conditions)和死锁线程。concurrent包很好的解决了这些问题,为我们提供了更实用的并发程序模型。
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class MyExecutor extends Thread { private int index; public MyExecutor(int i) { this.index = i; } public void run() { try { System.out.println("[" + this.index + "] start...."); Thread.sleep((int) (Math.random() * 1000)); System.out.println("[" + this.index + "] end."); }catch (Exception e) { e.printStackTrace(); } } public static void main(String args[]) { ExecutorService service = Executors.newFixedThreadPool(4); for (int i = 0; i < 10; i++) { service.execute(new MyExecutor(i)); // service.submit(new MyExecutor(i)); } System.out.println("submit finish"); service.shutdown(); } }虽然打印了一些信息,但是看的不是非常清晰,这个线程池是如何工作的,我们来将休眠的时间调长10倍。
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; public class MySemaphore extends Thread { private Semaphore position; private int id; public MySemaphore(int i, Semaphore s) { this.id = i; this.position = s; } public void run() { try { //有没有空厕所 if (position.availablePermits() > 0) { System.out.println("顾客[" + this.id + "]进入厕所,有空位"); }else { System.out.println("顾客[" + this.id + "]进入厕所,没空位,排队"); } //获取到空厕所了 position.acquire(); System.out.println("顾客[" + this.id + "]获得坑位"); //使用中... Thread.sleep((int) (Math.random() * 1000)); System.out.println("顾客[" + this.id + "]使用完毕"); //厕所使用完之后释放 position.release(); }catch (Exception e) { e.printStackTrace(); } } public static void main(String args[]) { ExecutorService list = Executors.newCachedThreadPool(); Semaphore position = new Semaphore(2);//只有两个厕所 //有十个人 for (int i = 0; i < 10; i++) { list.submit(new MySemaphore(i + 1, position)); } list.shutdown(); position.acquireUninterruptibly(2); System.out.println("使用完毕,需要清扫了"); position.release(2); } }
class X { private final ReentrantLock lock = new ReentrantLock(); // ... public void m() { lock.lock(); // block until condition holds try { // ... method body }finally { lock.unlock() } } }
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.locks.ReentrantLock; public class MyReentrantLock extends Thread { TestReentrantLock lock; private int id; public MyReentrantLock(int i, TestReentrantLock test) { this.id = i; this.lock = test; } public void run() { lock.print(id); } public static void main(String args[]) { ExecutorService service = Executors.newCachedThreadPool(); TestReentrantLock lock = new TestReentrantLock(); for (int i = 0; i < 10; i++) { service.submit(new MyReentrantLock(i, lock)); } service.shutdown(); } } class TestReentrantLock { private ReentrantLock lock = new ReentrantLock(); public void print(int str) { try { lock.lock(); System.out.println(str + "获得"); Thread.sleep((int) (Math.random() * 1000)); }catch (Exception e) { e.printStackTrace(); }finally { System.out.println(str + "释放"); lock.unlock(); } } }
import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; public class MyBlockingQueue extends Thread { public static BlockingQueue<String> queue = new LinkedBlockingQueue<String>(3); private int index; public MyBlockingQueue(int i) { this.index = i; } public void run() { try { queue.put(String.valueOf(this.index)); System.out.println("{" + this.index + "} in queue!"); } catch (Exception e) { e.printStackTrace(); } } public static void main(String args[]) { ExecutorService service = Executors.newCachedThreadPool(); for (int i = 0; i < 10; i++) { service.submit(new MyBlockingQueue(i)); } Thread thread = new Thread() { public void run() { try { while (true) { Thread.sleep((int) (Math.random() * 1000)); if (MyBlockingQueue.queue.isEmpty()) break; String str = MyBlockingQueue.queue.take(); System.out.println(str + " has take!"); } } catch (Exception e) { e.printStackTrace(); } } }; service.submit(thread); service.shutdown(); } }
import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class MyCompletionService implements Callable<String> { private int id; public MyCompletionService(int i) { this.id = i; } public static void main(String[] args) throws Exception { ExecutorService service = Executors.newCachedThreadPool(); CompletionService<String> completion = new ExecutorCompletionService<String>(service); for (int i = 0; i < 10; i++) { completion.submit(new MyCompletionService(i)); } for (int i = 0; i < 10; i++) { System.out.println(completion.take().get()); } service.shutdown(); } public String call() throws Exception { Integer time = (int) (Math.random() * 1000); try { System.out.println(this.id + " start"); Thread.sleep(time); System.out.println(this.id + " end"); }catch (Exception e) { e.printStackTrace(); } return this.id + ":" + time; } }
import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; 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();// 一直阻塞 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(); } }
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 { // 徒步需要的时间: 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; private CyclicBarrier barrier; private String tourName; public Tour(CyclicBarrier barrier, String tourName, int[] times) { this.times = times; this.tourName = tourName; this.barrier = barrier; } public void run() { try { Thread.sleep(times[0] * 1000); System.out.println(now() + tourName + " Reached Shenzhen"); 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) { // 三个旅行团 CyclicBarrier barrier = new CyclicBarrier(3); ExecutorService exec = Executors.newFixedThreadPool(3); exec.submit(new Tour(barrier, "WalkTour", timeWalk)); exec.submit(new Tour(barrier, "SelfTour", timeSelf)); // 当我们把下面的这段代码注释后,会发现,程序阻塞了,无法继续运行下去。 exec.submit(new Tour(barrier, "BusTour", timeBus)); exec.shutdown(); } }
import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class MyFutureTask { /** * @param args * @throws InterruptedException * @throws ExecutionException * @throws InterruptedException * @throws ExecutionException */ public static void main(String[] args) throws InterruptedException, ExecutionException { final ExecutorService exe=Executors.newFixedThreadPool(3); Callable<String> call=new Callable<String>(){ public String call() throws InterruptedException { return "Thread is finished"; } }; Future<String> task=exe.submit(call); String obj=task.get(); System.out.println(obj+"进程结束"); System.out.println("总进程结束"); exe.shutdown(); } } class MyThreadTest implements Runnable { private String str; public MyThreadTest(String str) { this.str = str; } public void run() { this.setStr("allen"+str); } public void addString(String str) { this.str = "allen:" + str; } public String getStr() { return str; } public void setStr(String str) { this.str = str; } }
import static java.util.concurrent.TimeUnit.SECONDS; import java.util.Date; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; 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); } }