[关闭]
@1234567890 2016-10-12T11:59:06.000000Z 字数 10608 阅读 2260

concurrent包详解

java


第一部分 Atomic数据类型

这部分都被放在java.util.concurrent.atomic这个包里面,实现了原子化操作的数据类型,包括 Boolean, Integer, Long, 和Referrence这四种类型以及这四种类型的数组类型。

  1. public class AtomicDemo {
  2. private static int count =1000;
  3. private static AtomicInteger result= new AtomicInteger(0);
  4. static class Work implements Runnable{
  5. private CountDownLatch latch;
  6. Work(CountDownLatch latch){
  7. this.latch = latch;
  8. }
  9. public void run() {
  10. try {
  11. for (int i = 0; i < count; i++) {
  12. result.incrementAndGet();
  13. }
  14. }finally {
  15. latch.countDown();
  16. }
  17. }
  18. }
  19. public static void main(String[] args) throws InterruptedException {
  20. CountDownLatch l = new CountDownLatch(2);
  21. Thread thread1 = new Thread(new Work(l));
  22. Thread thread2 = new Thread(new Work(l));
  23. thread1.start();
  24. thread2.start();
  25. l.await();
  26. System.out.println(result);
  27. }
  28. }

第二部分 锁

这部分都被放在java.util.concurrent.lock这个包里面,实现了并发操作中的几种类型的锁

  1. public interface Lock {
  2. void lock();
  3. void lockInterruptibly() throws InterruptedException;
  4. boolean tryLock();
  5. boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
  6. void unlock();
  7. Condition newCondition();
  8. }

Lock接口中每个方法的使用,lock()、tryLock()、tryLock(long time, TimeUnit unit)和lockInterruptibly()是用来获取锁的。unLock()方法是用来释放锁的。

锁的几个方法介绍

  1. Lock lock = ...;
  2. lock.lock();
  3. try{
  4. //处理任务
  5. }catch(Exception ex){
  6. }finally{
  7. lock.unlock(); //释放锁
  8. }
  1. Lock lock = ...;
  2. if(lock.tryLock()) {
  3. try{
  4. //处理任务
  5. }catch(Exception ex){
  6. }finally{
  7. lock.unlock(); //释放锁
  8. }
  9. }else {
  10. //如果不能获取锁,则直接做其他事情
  11. }
  1. public void method() throws InterruptedException {
  2. lock.lockInterruptibly();
  3. try {
  4. //.....
  5. }
  6. finally {
  7. lock.unlock();
  8. }
  9. }
  1. public class Test {
  2. private ArrayList<Integer> arrayList = new ArrayList<Integer>();
  3. private Lock lock = new ReentrantLock(); //注意这个地方
  4. public static void main(String[] args) {
  5. final Test test = new Test();
  6. new Thread(){
  7. public void run() {
  8. test.insert(Thread.currentThread());
  9. };
  10. }.start();
  11. new Thread(){
  12. public void run() {
  13. test.insert(Thread.currentThread());
  14. };
  15. }.start();
  16. }
  17. public void insert(Thread thread) {
  18. lock.lock();
  19. try {
  20. System.out.println(thread.getName()+"得到了锁");
  21. for(int i=0;i<5;i++) {
  22. arrayList.add(i);
  23. }
  24. } catch (Exception e) {
  25. // TODO: handle exception
  26. }finally {
  27. System.out.println(thread.getName()+"释放了锁");
  28. lock.unlock();
  29. }
  30. }
  31. }

第三部分 java集合框架中的一些数据结构的并发实现

  1. static final class Segment<K,V> extends ReentrantLock implements Serializable {
  2. transient volatile int count;
  3. transient int modCount;
  4. transient int threshold;
  5. transient volatile HashEntry<K,V>[] table;
  6. final float loadFactor;
  7. }
  8. static final class HashEntry<K,V> {
  9. final K key;
  10. final int hash;
  11. volatile V value;
  12. final HashEntry<K,V> next;
  13. }
  1. boolean offer(E e); //用来向队尾存入元素,如果队列满,则等待一定的时间,当时间期限达到时,如果还没有插入成功,则返回false;否则返回true;
  2. E poll(); //用来从队首取元素,如果队列空,则等待一定的时间,当时间期限达到时,如果取到,则返回null;否则返回取得的元素;
  3. void put(E e) throws InterruptedException; //用来向队尾存入元素,如果队列满,则等待;
  4. E take() throws InterruptedException; //用来从队首取元素,如果队列为空,则等待
  1. //以ArrayBlockingQueue为例,思路是生产者 消费者 模式
  2. public void put(E e) throws InterruptedException {
  3. if (e == null) throw new NullPointerException();
  4. final E[] items = this.items;
  5. final ReentrantLock lock = this.lock;
  6. lock.lockInterruptibly();
  7. try {
  8. try {
  9. while (count == items.length)
  10. notFull.await();
  11. } catch (InterruptedException ie) {
  12. notFull.signal(); // propagate to non-interrupted thread
  13. throw ie;
  14. }
  15. insert(e);
  16. } finally {
  17. lock.unlock();
  18. }
  19. }
  20. private void insert(E x) {
  21. items[putIndex] = x;
  22. putIndex = inc(putIndex);
  23. ++count;
  24. notEmpty.signal();
  25. }
  1. /**在添加的时候是需要加锁的,否则多线程写的时候会Copy出N个副本出来
  2. * Appends the specified element to the end of this list.
  3. *
  4. * @param e element to be appended to this list
  5. * @return <tt>true</tt> (as specified by {@link Collection#add})
  6. */
  7. public boolean add(E e) {
  8. final ReentrantLock lock = this.lock;
  9. lock.lock();
  10. try {
  11. Object[] elements = getArray();
  12. int len = elements.length;
  13. Object[] newElements = Arrays.copyOf(elements, len + 1);
  14. newElements[len] = e;
  15. setArray(newElements);
  16. return true;
  17. } finally {
  18. lock.unlock();
  19. }
  20. }

第四部分 多线程任务执行

--类-- --功能--
Callable Runable 被执行的任务
Executor 执行任务
Future 异步提交任务的返回数据
Executors 为Executor,ExecutorService,ScheduledExecutorService,ThreadFactory和Callable类提供了一些工具方法。
  1. V call() throws Exception;
  1. public abstract void run();
  1. V get() //阻塞方法,等待线程返回
  2. V get(long timeout, TimeUnit unit) //等待线程一段时间,如果未返回,则抛出异常
  1. Future<?> submit(Runnable task); //如果线程运行完成,返回null
  2. <T> Future<T> submit(Callable<T> task); //返回线程运行结果
  3. void execute(Runnable command);
  4. void shutdown(); //关闭线程池

第五部分 线程管理类

这部分主要是对线程集合的管理的实现,有CyclicBarrier, CountDownLatch,Exchanger等一些类

  1. public CountDownLatch(int count) { }; //参数count为计数值
  2. public void await() throws InterruptedException { }; //调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行
  3. public boolean await(long timeout, TimeUnit unit) throws InterruptedException { }; //和await()类似,只不过等待一定的时间后count值还没变为0的话就会继续执行
  4. public void countDown() { }; //将count值减1
  1. /**
  2. *比如有一个任务A,它要等待其他4个任务执行完毕之后才能执行。
  3. **/
  4. public class Test {
  5. public static void main(String[] args) {
  6. final CountDownLatch latch = new CountDownLatch(2);
  7. new Thread(){
  8. public void run() {
  9. try {
  10. System.out.println("子线程"+Thread.currentThread().getName()+"正在执行");
  11. Thread.sleep(3000);
  12. System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕");
  13. latch.countDown();
  14. } catch (InterruptedException e) {
  15. e.printStackTrace();
  16. }
  17. };
  18. }.start();
  19. new Thread(){
  20. public void run() {
  21. try {
  22. System.out.println("子线程"+Thread.currentThread().getName()+"正在执行");
  23. Thread.sleep(3000);
  24. System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕");
  25. latch.countDown();
  26. } catch (InterruptedException e) {
  27. e.printStackTrace();
  28. }
  29. };
  30. }.start();
  31. try {
  32. System.out.println("等待2个子线程执行完毕...");
  33. latch.await();
  34. System.out.println("2个子线程已经执行完毕");
  35. System.out.println("继续执行主线程");
  36. } catch (InterruptedException e) {
  37. e.printStackTrace();
  38. }
  39. }
  40. }
  1. public CyclicBarrier(int parties, Runnable barrierAction) {}
  2. public CyclicBarrier(int parties) {}
  3. public int await() throws InterruptedException, BrokenBarrierException { }; //挂起当前线程,直至所有线程都到达barrier状态再同时执行后续任务
  4. public int await(long timeout, TimeUnit unit)throws InterruptedException,BrokenBarrierException,TimeoutException { };
  1. /**
  2. *有若干个线程都要进行写数据操作,并且只有所有线程都完成写数据操作之后,这些线程才能继续做后面的事情
  3. **/
  4. public class Test {
  5. public static void main(String[] args) {
  6. int N = 4;
  7. CyclicBarrier barrier = new CyclicBarrier(N,new Runnable() {
  8. //想在所有线程写入操作完之后,进行额外的其他操作可以为CyclicBarrier提供Runnable参数
  9. @Override
  10. public void run() {
  11. System.out.println("当前线程"+Thread.currentThread().getName());
  12. }
  13. });
  14. for(int i=0;i<N;i++)
  15. new Writer(barrier).start();
  16. }
  17. static class Writer extends Thread{
  18. private CyclicBarrier cyclicBarrier;
  19. public Writer(CyclicBarrier cyclicBarrier) {
  20. this.cyclicBarrier = cyclicBarrier;
  21. }
  22. @Override
  23. public void run() {
  24. System.out.println("线程"+Thread.currentThread().getName()+"正在写入数据...");
  25. try {
  26. Thread.sleep(5000); //以睡眠来模拟写入数据操作
  27. System.out.println("线程"+Thread.currentThread().getName()+"写入数据完毕,等待其他线程写入完毕");
  28. cyclicBarrier.await();
  29. } catch (InterruptedException e) {
  30. e.printStackTrace();
  31. }catch(BrokenBarrierException e){
  32. e.printStackTrace();
  33. }
  34. System.out.println("所有线程写入完毕,继续处理其他任务...");
  35. }
  36. }
  37. }
  1. public Semaphore(int permits) {} //参数permits表示许可数目,即同时可以允许多少线程进行访问
  2. }
  3. public Semaphore(int permits, boolean fair) {} //这个多了一个参数fair表示是否是公平的,即等待时间越久的越先获取许可
  4. public void acquire() throws InterruptedException { } //获取一个许可,若无许可能够获得,则会一直等待,直到获得许可。
  5. public void acquire(int permits) throws InterruptedException { } //获取permits个许可
  6. public void release() { } //释放一个许可
  7. public void release(int permits) { } //释放permits个许可
  8. public boolean tryAcquire() { }; //尝试获取一个许可,若获取成功,则立即返回true,若获取失败,则立即返回false
  9. public boolean tryAcquire(long timeout, TimeUnit unit) throws InterruptedException { }; //尝试获取一个许可,若在指定的时间内获取成功,则立即返回true,否则则立即返回false
  10. public boolean tryAcquire(int permits) { }; //尝试获取permits个许可,若获取成功,则立即返回true,若获取失败,则立即返回false
  11. public boolean tryAcquire(int permits, long timeout, TimeUnit unit) throws InterruptedException { }; //尝试获取permits个许可,若在指定的时间内获取成功,则立即返回true,否则则立即返回false
  1. /**
  2. *一个工厂有5台机器,但是有8个工人,一台机器同时只能被一个工人使用,只有使用完了,其他工人才能继续使用。
  3. **/
  4. public class Test {
  5. public static void main(String[] args) {
  6. int N = 8; //工人数
  7. Semaphore semaphore = new Semaphore(5); //机器数目
  8. for(int i=0;i<N;i++)
  9. new Worker(i,semaphore).start();
  10. }
  11. static class Worker extends Thread{
  12. private int num;
  13. private Semaphore semaphore;
  14. public Worker(int num,Semaphore semaphore){
  15. this.num = num;
  16. this.semaphore = semaphore;
  17. }
  18. @Override
  19. public void run() {
  20. try {
  21. semaphore.acquire();
  22. System.out.println("工人"+this.num+"占用一个机器在生产...");
  23. Thread.sleep(2000);
  24. System.out.println("工人"+this.num+"释放出机器");
  25. semaphore.release();
  26. } catch (InterruptedException e) {
  27. e.printStackTrace();
  28. }
  29. }
  30. }
  31. }
  1. public class ExchangerDemo {
  2. public static void main(String[] args) {
  3. Exchanger<List<Integer>> exchanger = new Exchanger<List<Integer>>();
  4. new Consumer(exchanger).start();
  5. new Producer(exchanger).start();
  6. }
  7. }
  8. class Producer extends Thread {
  9. List<Integer> list = new ArrayList<Integer>();
  10. Exchanger<List<Integer>> exchanger = null;
  11. public Producer(Exchanger<List<Integer>> exchanger) {
  12. super();
  13. this.exchanger = exchanger;
  14. }
  15. @Override
  16. public void run() {
  17. Random rand = new Random();
  18. for(int i=0; i<10; i++) {
  19. list.clear();
  20. list.add(rand.nextInt(10000));
  21. list.add(rand.nextInt(10000));
  22. list.add(rand.nextInt(10000));
  23. list.add(rand.nextInt(10000));
  24. list.add(rand.nextInt(10000));
  25. try {
  26. list = exchanger.exchange(list);
  27. } catch (InterruptedException e) {
  28. // TODO Auto-generated catch block
  29. e.printStackTrace();
  30. }
  31. }
  32. }
  33. }
  34. class Consumer extends Thread {
  35. List<Integer> list = new ArrayList<Integer>();
  36. Exchanger<List<Integer>> exchanger = null;
  37. public Consumer(Exchanger<List<Integer>> exchanger) {
  38. super();
  39. this.exchanger = exchanger;
  40. }
  41. @Override
  42. public void run() {
  43. for(int i=0; i<10; i++) {
  44. try {
  45. list = exchanger.exchange(list);
  46. } catch (InterruptedException e) {
  47. // TODO Auto-generated catch block
  48. e.printStackTrace();
  49. }
  50. System.out.print(list.get(0)+", ");
  51. System.out.print(list.get(1)+", ");
  52. System.out.print(list.get(2)+", ");
  53. System.out.print(list.get(3)+", ");
  54. System.out.println(list.get(4)+", ");
  55. }
  56. }
  57. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注