Java高并发程序设计(五)JDK并发包1

1. 各种同步控制工具的使用

1.1. ReentrantLock
可重入:单线程可以重复进入,但要重复退出。

可中断:lockInterruptibly()。

可限时:超时不能获得锁,就返回false,不会永久等待构成死锁
公平锁:先来先得
public ReentrantLock(boolean fair)
public static ReentrantLock fairLock = new ReentrantLock(true);

package com.thread.chapter05;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 可重入锁
 * Created by chenbin on 2019\8\16 0016.
 */
public class ReenterLock implements Runnable {
    public static ReentrantLock lock = new ReentrantLock();
    public static int i = 0;

    public void run() {
        for (int j = 0;j < 10000000;j++) {
            //访问共享数据 i 要加锁
            lock.lock();
            try{
                i++;
            }finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ReenterLock r1 = new ReenterLock();
        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r1);

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.print(i);
    }
}
package com.thread.chapter05;

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

/**
 * 可重入锁,设置获取时间
 * Created by chenbin on 2019\8\16 0016.
 */
public class TimeLock implements Runnable {
    public static ReentrantLock lock = new ReentrantLock();

    public void run() {
        try {
            if (lock.tryLock(5, TimeUnit.SECONDS)) {
                Thread.sleep(6000);
            } else {
                System.out.print("get lock failed.");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        TimeLock r1 = new TimeLock();
        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r1);

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

1.2. Condition
概述 :类似于 Object.wait()和Object.notify();与ReentrantLock结合使用。
主要接口:

void await() throws InterruptedException;
void awaitUninterruptibly();
long awaitNanos(long nanosTimeout) throws InterruptedException;
boolean await(long time, TimeUnit unit) throws InterruptedException;
boolean awaitUntil(Date deadline) throws InterruptedException;
void signal();
void signalAll();
API详解:

await()方法会使当前线程等待,同时释放当前锁,当其他线程中使用signal()时或者signalAll()方法时,线
程会重新获得锁并继续执行。或者当线程被中断时,也能跳出等待。这和Object.wait()方法很相似。
awaitUninterruptibly()方法与await()方法基本相同,但是它并不会再等待过程中响应中断。
singal()方法用于唤醒一个在等待中的线程。相对的singalAll()方法会唤醒所有在等待中的线程。

这和Obejct.notify()方法很类似。

package com.thread.chapter05;

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

/**
 * 可重入锁,条件 的使用
 * Created by chenbin on 2019\8\16 0016.
 */
public class ReenterConditionLock implements Runnable {
    public static ReentrantLock lock = new ReentrantLock();
    public static Condition condition = lock.newCondition();

    public void run() {
        try {
            lock.lock();
            condition.await();
            System.out.print("Thread is going on.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ReenterConditionLock r1 = new ReenterConditionLock();
        Thread t1 = new Thread(r1);
        t1.start();

        Thread.sleep(2000);
        lock.lock();
        //通知t1继续执行
        condition.signal();
        lock.unlock();
    }
}

1.3. Semaphore
概述:共享锁,运行多个线程同时临界区
主要接口:

public void acquire()
public void acquireUninterruptibly()
public boolean tryAcquire()
public boolean tryAcquire(long timeout, TimeUnit unit)
public void release()

package com.thread.chapter05;

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

/**
 *  信号量的使用
 * Created by chenbin on 2019\8\16 0016.
 */
public class SemapDemo implements Runnable {
    public static Semaphore semaphore = new Semaphore(5);

    public void run() {
        try {
            semaphore.acquire();
            Thread.sleep(2000);
            System.out.println(Thread.currentThread().getId() +
                    "done.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService exec = Executors.newFixedThreadPool(20);
        final SemapDemo demo = new SemapDemo();
        for (int i=0;i<20;i++) {
            exec.submit(demo);
        }
        exec.shutdown();
    }
}

1.4. ReadWriteLock 
概述:ReadWriteLock是JDK5中提供的读写分离锁。
访问情况:

读-读不互斥:读读之间不阻塞。
读-写互斥:读阻塞写,写也会阻塞读。
写-写互斥:写写阻塞

 
非阻塞阻塞
阻塞阻塞

主要接口:

private static ReentrantReadWriteLock readWriteLock=new ReentrantReadWriteLock();
private static Lock readLock = readWriteLock.readLock();
private static Lock writeLock = readWriteLock.writeLock();

package com.thread.chapter05;

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

/**
 * 读写锁使用场景:
 * 当读操作远大于写,则读写锁可以发挥很大作用。
 * 这段代码使用读写锁,程序大约两秒就可以运行完成,而使用注释中的重入锁,则需要20秒才可以运行完成。
 * Created by chenbin on 2019\8\27 0027.
 */
public class ReadWriteLockDemo {
    private static ReentrantLock lock = new ReentrantLock();
    private static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private static Lock readLock = readWriteLock.readLock();
    private static Lock writeLock = readWriteLock.readLock();
    private int value;

    //读方法
    public Object handleRead(Lock lock) throws InterruptedException {
        try {
            lock.lock();
            Thread.sleep(1000);
            return value;
        } finally {
            lock.unlock();
        }
    }

    //写方法
    public void handleWrite(Lock lock, int index) throws InterruptedException {
        try {
            lock.lock();
            Thread.sleep(1000);
            value = index;
        } finally {
            lock.unlock();
        }
    }

    //测试main()函数
    public static void main(String[] args) {
        final ReadWriteLockDemo exp = new ReadWriteLockDemo();

        Runnable readRunnable = new Runnable() {
            @Override
            public void run() {
                try {
                    exp.handleRead(readLock);
//                    exp.handleRead(lock);
                    System.out.println("readRunnable线程执行当前时间戳:" + System.currentTimeMillis());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        Runnable writeRunnable = new Runnable() {
            @Override
            public void run() {
                try {
                    exp.handleWrite(writeLock, new Random().nextInt());
//                    exp.handleWrite(lock, new Random().nextInt());
                    System.out.println("writeRunnable线程执行当前时间戳:" + System.currentTimeMillis());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        //18个线程读数据
        for (int i = 0; i < 18; i++) {
            new Thread(readRunnable).start();
        }
        //2个线程写数据
        for (int i = 18; i < 20; i++) {
            new Thread(writeRunnable).start();
        }
    }

}

1.5. CountDownLatch
概述:倒数计时器
一种典型的场景就是火箭发射。在火箭发射前,为了保证万无一失,往往还要进行各项设备、仪器的检查。
只有等所有检查完毕后,引擎才能点火。这种场景就非常适合使用CountDownLatch。它可以使得点火线程
,等待所有检查线程全部完工后,再执行。
主要接口:

static final CountDownLatch end = new CountDownLatch(10);
end.countDown();
end.await();

package com.thread.chapter05;

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

/**
 * 倒数计时器
 * Created by chenbin on 2019\8\16 0016.
 */
public class CountDownLatchDemo implements Runnable {
    public static CountDownLatch end = new CountDownLatch(10);

    public void run() {
        try {
            //模拟检查任务
            Thread.sleep(new Random().nextInt(10)*1000);
            System.out.println("check done.");
            end.countDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {

        }
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService exec = Executors.newFixedThreadPool(10);
        final CountDownLatchDemo demo = new CountDownLatchDemo();
        for (int i = 0;i < 10;i++) {
            exec.submit(demo);
        }
        //等待检查
        end.await();
        System.out.println("Fire !");
        exec.shutdown();
    }
}

示意图:

1.6. CyclicBarrier
概述:Cyclic意为循环,也就是说这个计数器可以反复使用。比如,假设我们将计数器设置为10。那么凑齐第一批

10个线程后,计数器就会归零,然后接着凑齐下一批10个线程。
主要接口: 

public CyclicBarrier(int parties, Runnable barrierAction)
barrierAction就是当计数器一次计数完成后,系统会执行的动作
await();

package com.thread.chapter05;

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

/**
 * 循环栅栏
 * Created by chenbin on 2019\8\16 0016.
 */
public class CyclicBarrierDemo {
    //每个线程的任务
    public static class Soldier implements Runnable {
        private String soldier;
        private final CyclicBarrier cyclicBarrier;

        Soldier(CyclicBarrier cyclicBarrier,String soldier) {
            this.cyclicBarrier = cyclicBarrier;
            this.soldier = soldier;
        }

        public void run() {
            try {
                //等待栅栏位满
                cyclicBarrier.await();
                doWork();
                //等待栅栏所有线程工作结束
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }finally {

            }
        }

        //
        private void doWork() {
            try {
                Thread.sleep(Math.abs(new Random().nextInt()%10000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(soldier + "任务完成");
        }
    }

    //栅栏位满后需要执行的动作
    public static class BarrierRun implements Runnable {
        boolean flag;
        int N;

        public BarrierRun(boolean flag,int N) {
            this.flag = flag;
            this.N = N;
        }

        public void run() {
            if (flag) {
                System.out.println(N +"个士兵任务完成。");
            } else {
                System.out.println(N +"个士兵集合和完毕");
                flag = true;
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        final int N = 10;
        Thread[] allSoldier = new Thread[N];
        boolean flag = false;
        CyclicBarrier cyclic = new CyclicBarrier(N,new BarrierRun(flag,N));

        //设置屏障点
        System.out.println("集合队伍。");
        for (int i = 0;i < N; ++i) {
            System.out.println("士兵"+i+"报道。");
            allSoldier[i] = new Thread(new Soldier(cyclic,"士兵"+i));
            allSoldier[i].start();
//            if (i == 5) {
//                allSoldier[i].interrupt();
//            }
        }

    }
}


示意图:


1.7. LockSupport
概述:提供线程阻塞原语。
主要接口:

LockSupport.park();
LockSupport.unpark(t1);
与suspend()比较:不容易引起线程冻结。
中断响应:

能够响应中断,但不抛出异常。
中断响应的结果是,park()函数的返回,可以从Thread.interrupted()得到中断标志。

package com.thread.chapter05;

import java.util.concurrent.locks.LockSupport;

/**
 * Created by chenbin on 2019\8\16 0016.
 */
public class LockSupportDemo {
    public static Object u  = new Object();
    
    public static class ChangeObjectThread extends Thread {
        public ChangeObjectThread(String name) {
            super.setName(name);
        }

        @Override
        public void run() {
            synchronized (u) {
                System.out.println("in "+getName());
                LockSupport.park();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ChangeObjectThread t1 = new ChangeObjectThread("t1");
        ChangeObjectThread t2 = new ChangeObjectThread("t2");

        t1.start();
        Thread.sleep(1000);
        t2.start();
        LockSupport.unpark(t1);
        LockSupport.unpark(t2);
        t1.join();
        t2.join();

    }
}

1.8. ReentrantLock 的实现(需读源码)
CAS状态
等待队列
park()

2. 并发容器及典型源码分析

2.1. 集合包装
HashMap:同步的Collections.synchronizedMap
public static Map m=Collections.synchronizedMap(new HashMap());
List:synchronizedList
Set:synchronizedSet
2.2. ConcurrentHashMap

高性能线程安全的HashMap
2.3. BlockingQueue

阻塞队列
2.4. ConcurrentLinkedQueue

3.死锁案例及检测解决

死锁的形成通常是相互持有了对方线程正在等待的资源,导致资源的不到释放。又或者是循环死锁。

package com.thread.chapter05.deadlock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 死锁案例,以及死锁检测解决(中断死锁线程)
 * Created by chenbin on 2019\8\16 0016.
 */
public class DeadLockDemo implements Runnable {
    public int lock;
    public static ReentrantLock lock1 = new ReentrantLock();
    public static ReentrantLock lock2 = new ReentrantLock();

    public DeadLockDemo(int lock) {
        this.lock = lock;
    }

    public void run() {
        try {
            if (lock == 1) {
                lock1.lockInterruptibly();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {

                }
                lock2.lockInterruptibly();
            } else {
                lock2.lockInterruptibly();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {

                }
                lock1.lockInterruptibly();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (lock1.isHeldByCurrentThread()) {
                lock1.unlock();
            }
            if (lock2.isHeldByCurrentThread()) {
                lock2.unlock();
            }
            System.out.print(Thread.currentThread().getId() +
                    ":线程退出");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        DeadLockDemo r1 = new DeadLockDemo(1);
        DeadLockDemo r2 = new DeadLockDemo(2);
        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r2);

        t1.start();
        t2.start();
        Thread.sleep(1000);
        //下面代码注释后,就是死锁案例。这个方法可以检测死锁线程,并且中断进入死锁的线程。
        DeadlockChecker.check();
    }
}
package com.thread.chapter05.deadlock;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;

/**
 * 死锁检测,中断死锁线程
 * Created by chenbin on 2019\8\18 0018.
 */
public class DeadlockChecker {
    private final static ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
    final static Runnable deadlockCheck = new Runnable() {
        public void run() {
            while (true) {
                long[] deadlockThreadIds = mbean.findDeadlockedThreads();
                if (deadlockThreadIds != null) {
                    ThreadInfo[] threadInfos = mbean.getThreadInfo(deadlockThreadIds);
                    for (Thread t : Thread.getAllStackTraces().keySet()) {
                        for (int i = 0;i < threadInfos.length;i++) {
                            if (t.getId() == threadInfos[i].getThreadId()) {
                                t.interrupt();
                            }
                        }

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

                }
            }
        }
    };

    public static void check() {
        Thread t = new Thread(deadlockCheck);
        t.setDaemon(true);
        t.start();
    }
}

源代码可以在github上下载:https://github.com/chenbin911029/mutiThread 

本文的类文件在 com.thread.chapter05 包下。

备注:本文为JAVA高并发程序设计(葛一鸣著)读书笔记,以及自身的整理和实践。

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值