【Java互联网架构学习----003--01】concurrent.until下的工具类

1、CyclicBarrier: 中文意思是“循环栅栏”。大概的意思就是一个可循环利用的屏障。作用就是会让所有线程都等待完成后才会继续下一步行动。例子,就像生活中我们会约朋友们到某个餐厅一起吃饭,有些朋友可能会早到,有些朋友可能会晚到,但是这个餐厅规定必须等到所有人到齐之后才会让我们进去。这里的朋友们就是各个线程,餐厅就是 CyclicBarrier。

package com.neo.study003.radio01;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author liyy
 * @date 2020/5/20 23:16
 */
public class UseCyclicBarrier {

    static class Runner implements Runnable{
        private CyclicBarrier cyclicBarrier;
        private String name;

        public Runner(CyclicBarrier cyclicBarrier, String name) {
            this.cyclicBarrier = cyclicBarrier;
            this.name = name;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(1000*(new Random()).nextInt(5));
                System.out.println(name+"准备Ok。。。");
                cyclicBarrier.await();
            }catch (InterruptedException e){
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
            System.out.println(name+" 准备好了,开始!!!");
        }
    }

    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        executorService.submit(new Thread(new Runner(cyclicBarrier,"name1")));
        executorService.submit(new Thread(new Runner(cyclicBarrier,"name2")));
        executorService.submit(new Thread(new Runner(cyclicBarrier,"name3")));
        executorService.shutdown();
    }
}

2、CountDownLatch: 是一个同步工具类,用来协调多个线程之间的同步,或者说起到线程之间的通信(而不是用作互斥的作用)。CountDownLatch能够使一个线程在等待另外一些线程完成各自工作之后,再继续执行。使用一个计数器进行实现。计数器初始值为线程的数量。当每一个线程完成自己任务后,计数器的值就会减一。当计数器的值为0时,表示所有的线程都已经完成一些任务,然后在CountDownLatch上等待的线程就可以恢复执行接下来的任务。

package com.neo.study003.radio01;

import java.util.concurrent.CountDownLatch;

/**
 * @author liyy
 * @date 2020/5/20 22:55
 */
public class UseCountDownLatch {
    public static void main(String[] args) {
        final CountDownLatch countDownLatch = new CountDownLatch(2);
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("进入t1线程,等待其他线程完成操作。。。。。");
                try {
                    countDownLatch.await();
                    System.out.println("t1线程继续执行。。。。");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "t1");

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("进入t2线程,开始操作。。。。。");
                    Thread.sleep(3000);
                    countDownLatch.countDown();
                    System.out.println("t2线程执行完成,通知t1。。。。");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "t1");

        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("进入t3线程,开始操作。。。。。");
                    Thread.sleep(4000);
                    countDownLatch.countDown();
                    System.out.println("t3线程执行完成,通知t1。。。。");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "t1");

        t1.start();
        t2.start();
        t3.start();
    }
}

3.Callable: Callable接口类似于Runnable,但是Runnable不会返回结果,并且无法抛出返回结果的异常,而Callable功能更强大一些,被线程执行后,可以返回值,这个返回值可以被Future拿到,也就是说,Future可以拿到异步执行任务的返回值
Callable 与 Runnable 相比有以下 2 点不同:
Callable 可以在任务结束的时候提供一个返回值,Runnable 无法提供这个功能
Callable 的 call 方法分可以抛出异常,而 Runnable 的 run 方法不能抛出异常。

package com.neo.study003.radio01;

import java.util.concurrent.*;

/**
 * @author liyy
 * @date 2020/5/21 20:56
 */
public class UseFuture implements Callable<String> {

    private String param;

    public UseFuture(String param) {
        this.param = param;
    }

    @Override
    public String call() throws Exception {
        Thread.sleep(5000);
        String result = this.param + "操作处理完成";
        return result;
    }


    public static void main(String[] args) throws Exception {
        String param="select查询1";
        String param2="select查询2";
        FutureTask<String> future = new FutureTask<String>(new UseFuture(param));
        FutureTask<String> future2 = new FutureTask<String>(new UseFuture(param2));

        ExecutorService pool = Executors.newFixedThreadPool(2);

        Future<?> f = pool.submit(future);//启动一个线程去单独执行任务
        Future<?> f2 = pool.submit(future2);//启动一个线程去单独执行任务

        System.out.println("请求执行完毕");

        try {
            System.out.println("处理主线的业务逻辑...");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //Future.get方法是一个阻塞方法,当submit提交多个任务时,只有所有任务都完成后,
        // 才能使用get按照任务的提交顺序得到返回结果,
        // 所以一般需要使用Future.isDone先判断任务是否全部执行完成,完成后再使用Future.get得到结果
        System.out.println(future.get());
        System.out.println(future2.get());

        System.out.println(f.get());//
        System.out.println(f2.get());//
        pool.shutdown();
    }
}

4.Semaphore: Semaphore叫信号量,Semaphore有两个目的,第一个是多个共享资源互斥使用,第二个是并发线程数的控制。

package com.neo.study003.radio01;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author liyy
 * @date 2020/5/21 22:13
 */
public class UseSemaphore {

    public static void main(String[] args) {
        ExecutorService pool = Executors.newCachedThreadPool();
        //只能5个线程同时访问
        final Semaphore semaphore = new Semaphore(5);
        for (int i = 0; i < 20; i++) {
            final int NO=i;
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    //获取许可
                    try {
                        semaphore.acquire();
                        System.out.println("接受:"+NO);
                        Thread.sleep((long)Math.random()*10000);
                        semaphore.release();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
            pool.submit(runnable);
        }

        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 退出线程池
        pool.shutdown();
    }
}

5.可重入锁ReentrantLock: 可重入锁又名递归锁,是指在同一个线程在外层方法获取锁的时候,再进入该线程的内层方法会自动获取锁(前提锁对象得是同一个对象或者class),不会因为之前已经获取过还没释放而阻塞。Java中ReentrantLock和synchronized都是可重入锁,可重入锁的一个优点是可一定程度避免死锁

package com.neo.study003.radio01;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author liyy
 * @date 2020/5/21 23:32
 */
public class UseReentrantLock {

    private Lock lock = new ReentrantLock();

    public void method1() {
        try {
            lock.lock();
            System.out.println("当前线程:" + Thread.currentThread().getName() + "进入m1...");
            Thread.sleep(1000);
            System.out.println("当前线程:" + Thread.currentThread().getName() + "退出m1......");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void method2() {
        try {
            lock.lock();
            System.out.println("当前线程:" + Thread.currentThread().getName() + "进入m2...");
            Thread.sleep(1000);
            System.out.println("当前线程:" + Thread.currentThread().getName() + "退出m2......");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        UseReentrantLock useReentrantLock = new UseReentrantLock();
        final Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                useReentrantLock.method1();
                useReentrantLock.method2();
            }
        }, "t1");

        t1.start();
        
    }
}

Condition: lock可产生多个Condition,非常灵活

package com.neo.study003.radio01;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author liyy
 * @date 2020/5/21 23:32
 */
public class UseCondition {

    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();


    public void method1() {
        try {
            lock.lock();
            System.out.println("当前线程:" + Thread.currentThread().getName() + "进入m1...");
            Thread.sleep(3000);
            System.out.println("当前线程:" + Thread.currentThread().getName() + "释放锁......");
            condition.await();
            System.out.println("当前线程:" + Thread.currentThread().getName() + "m1继续执行......");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void method2() {
        try {
            lock.lock();
            System.out.println("当前线程:" + Thread.currentThread().getName() + "进入m1...");
            Thread.sleep(3000);
            System.out.println("当前线程:" + Thread.currentThread().getName() + "发出唤醒......");
            condition.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        UseCondition useReentrantLock = new UseCondition();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                useReentrantLock.method1();
            }
        }, "t1");
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                useReentrantLock.method2();
            }
        }, "t2");
        t1.start();
        t2.start();
    }
}

package com.neo.study003.radio01;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author liyy
 * @date 2020/5/21 23:32
 */
public class UseCondition {

    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();


    public void method1() {
        try {
            lock.lock();
            System.out.println("当前线程:" + Thread.currentThread().getName() + "进入m1...");
            condition1.await();
            System.out.println("当前线程:" + Thread.currentThread().getName() + "m1继续执行......");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void method2() {
        try {
            lock.lock();
            System.out.println("当前线程:" + Thread.currentThread().getName() + "进入m1...");
            condition1.await();
            System.out.println("当前线程:" + Thread.currentThread().getName() + "m2继续执行......");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void method3() {
        try {
            lock.lock();
            System.out.println("当前线程:" + Thread.currentThread().getName() + "进入m3...");
            condition2.await();
            System.out.println("当前线程:" + Thread.currentThread().getName() + "m3继续执行......");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void method4() {
        try {
            lock.lock();
            System.out.println("当前线程:" + Thread.currentThread().getName() + "进入m4...唤醒All操作");
            condition1.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void method5() {
        try {
            lock.lock();
            System.out.println("当前线程:" + Thread.currentThread().getName() + "进入m5...唤醒操作");
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        UseCondition useReentrantLock = new UseCondition();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                useReentrantLock.method1();
            }
        }, "t1");
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                useReentrantLock.method2();
            }
        }, "t2");
        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                useReentrantLock.method3();
            }
        }, "t3");
        Thread t4 = new Thread(new Runnable() {
            @Override
            public void run() {
                useReentrantLock.method4();
            }
        }, "t4");
        Thread t5 = new Thread(new Runnable() {
            @Override
            public void run() {
                useReentrantLock.method5();
            }
        }, "t5");
        t1.start();
        t2.start();
        t3.start();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t4.start();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t5.start();
    }
}

ReentrantReadWriteLock:
读写锁,核心就是实现读写分离的锁,在高并发访问下尤其是读多写少的情况下,性能远高于重入锁;读读共享,写写互斥,读写互斥

package com.neo.study003.radio01;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author liyy
 * @date 2020/6/6 13:06 使用读写锁
 */
public class UseReentrantReadWriteLock {

    private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private ReentrantReadWriteLock.ReadLock readLock = readWriteLock.readLock();
    private ReentrantReadWriteLock.WriteLock writeLock = readWriteLock.writeLock();

    public void read() {
        try {
            readLock.lock();
            System.out.println("当前线程:" + Thread.currentThread().getName() + "进入....");
            Thread.sleep(3000);
            System.out.println("当前线程:" + Thread.currentThread().getName() + "退出....");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            readLock.unlock();
        }
    }
    public void write() {
        try {
            writeLock.lock();
            System.out.println("当前线程:" + Thread.currentThread().getName() + "进入....");
            Thread.sleep(3000);
            System.out.println("当前线程:" + Thread.currentThread().getName() + "退出....");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            writeLock.unlock();
        }
    }

    public static void main(String[] args) {
        final UseReentrantReadWriteLock ulock = new UseReentrantReadWriteLock();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                ulock.read();
            }
        }, "t1");
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                ulock.read();
            }
        }, "t2");
        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                ulock.write();
            }
        }, "t3");
//        t1.start();
//        t2.start();

        t2.start();
        t3.start();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值