1.什么是JUC
java.util工具包
业务: 普通的线程代码, 之前都是用的thread或者runnable接口
但是相比于callable来说,thread没有返回值,且效率没有callable高
2.线程和进程
线程,进程
进程 : 一个运行中的程序的集合; 一个进程往往可以包含多个线程,至少包含一个线程
java默认有几个线程? 两个, main线程 和 gc线程
线程 : 线程(thread)是操作系统能够进行运算调度的最小单位。
对于java而言如何创建thread: 继承自thread,实现runnable接口,实现callable接口,线程池创建
Java真的可以开启线程吗 ? 开不了的,底层是用native关键词修饰.调用本地实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 public synchronized void start () { if (threadStatus != 0 ) throw new IllegalThreadStateException (); group.add(this ); boolean started = false ; try { start0(); started = true ; } finally { try { if (!started) { group.threadStartFailed(this ); } } catch (Throwable ignore) { } } } private native void start0 () ;
并发,并行
并发编程: 并发和并行
并发(多线程操作同一个资源,交替执行)
CPU一核, 模拟出来多条线程,天下武功,唯快不破,快速交替
并行(多个人一起行走, 同时进行)
CPU多核,多个线程同时进行 ; 使用线程池操作
1 2 3 4 5 public static void main (String[] args) { System.out.println(Runtime.getRuntime().availableProcessors()); }
并发编程的本质: 充分利用CPU的资源
所有的公司都很看重!
线程有几个状态?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public enum State { NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED; }
wait/sleep的区别
1.来自不同的类
wait来自object类, sleep来自线程类
2.关于锁的释放
wait会释放锁, sleep不会释放锁
3.使用的范围不同
wait必须在同步代码块中
sleep可以在任何地方睡
4.是否需要捕获异常
wait不需要捕获异常
sleep需要捕获异常
3.Lock锁(重点) 在java的锁的实现上就有共享锁和独占锁的区别,而这些实现都是基于AbstractQueuedSynchronizer对于共享同步和独占同步的支持。
独占模式
AbstractQueuedSynchronizer(AQS)使用一个volatile类型的int来作为同步变量,任何想要获得锁的线程都需要来竞争该变量,获得锁的线程可以继续业务流程的执行,而没有获得锁的线程会被放到一个FIFO的队列中去,等待再次竞争同步变量来获得锁。
锁的独占与共享
java并发包提供的加锁模式分为独占锁和共享锁,独占锁模式下,每次只能有一个线程能持有锁,ReentrantLock就是以独占方式实现的互斥锁。共享锁,则允许多个线程同时获取锁,并发访问 共享资源,如:ReadWriteLock。AQS的内部类Node定义了两个常量SHARED(共享)和EXCLUSIVE(独占),他们分别标识 AQS队列中等待线程的锁获取模式。
很显然,独占锁是一种悲观保守的加锁策略,它避免了读/写冲突,如果某个只读线程获取锁,则其他读线程都只能等待,这种情况下就限制了不必要的并发性,因为读操作并不会影响数据的一致性。共享锁则是一种乐观锁,它放宽了加锁策略,允许多个执行读操作的线程同时访问共享资源。 java 的并发包中提供了ReadWriteLock,读-写锁。**它允许一个资源可以被多个读操作访问,或者被一个写操作访问,但两者不能同时进行**。
锁的公平与非公平
锁的公平与非公平,是指线程请求获取锁的过程中,是否允许插队。在公平锁上,线程将按他们发出请求的顺序来获得锁;而非公平锁则允许在线程发出请求后立即尝试获取锁,如果可用则可直接获取锁,尝试失败才进行排队等待。ReentrantLock提供了两种锁获取方式,FairSyn和NofairSync。**结论:ReentrantLock是以独占锁的加锁策略实现的互斥锁,同时它提供了公平和非公平两种锁获取方式**。
AQS提供的模板方法
AQS提供了独占锁和共享锁必须实现的方法,具有独占锁功能的子类,它必须实现tryAcquire、tryRelease、isHeldExclusively等;共享锁功能的子类,必须实现tryAcquireShared和tryReleaseShared等方法,带有Shared后缀的方法都是支持共享锁加锁的语义。Semaphore是一种共享锁,ReentrantLock是一种独占锁。
独占锁获取锁时,设置节点模式为Node.EXCLUSIVE
1 2 3 4 5 public final void acquire (int arg) { if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) selfInterrupt(); }
共享锁获取锁,节点模式则为Node.SHARED
1 2 3 4 5 private void doAcquireShared (int arg) { final Node node = addWaiter(Node.SHARED); boolean failed = true ; ..... }
对ConditionObject的认识
ReentrantLock是独占锁,而且AQS的ConditionObject只能与ReentrantLock一起使用,它是为了支持条件队列的锁更方便。ConditionObject的signal和await方法都是基于独占锁的,如果线程非锁的独占线程,则会抛出IllegalMonitorStateException 。例如signalAll源码:
1 2 3 4 5 6 7 public final void signalAll () { if (!isHeldExclusively()) throw new IllegalMonitorStateException (); Node first = firstWaiter; if (first != null ) doSignalAll(first); }
我在想,既然Condtion是为了支持Lock的,为什么ConditionObject不作为ReentrantLock的内部类呢?对于实现锁功能的子类,直接扩展它就可以实现对条件队列的支持。但是,对于其它非锁语义的实现类如Semaphore、CountDownLatch等类来说,条件队列是无用的,也会给开发者扩展AQS带来困惑。总之,是各有利弊,大师们的思想,还需要仔细揣摩啊!
共享模式和独占模式的区别在于,独占模式只允许一个线程获得资源,而共享模式允许多个线程获得资源。
传统synchronized
本质: 队列和锁, synchronized 放在方法上锁的是this,放在代码块中锁的是()里面的对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 package com.kuang.demo01; import java.time.OffsetDateTime; public class SaleTicketDemo01 { public static void main (String[] args) { Ticket ticket = new Ticket (); new Thread (()->{ for (int i = 1 ; i < 40 ; i++) { ticket.sale(); } },"A" ).start(); new Thread (()->{ for (int i = 1 ; i < 40 ; i++) { ticket.sale(); } },"B" ).start(); new Thread (()->{ for (int i = 1 ; i < 40 ; i++) { ticket.sale(); } },"C" ).start(); } } class Ticket { private int number = 30 ; public synchronized void sale () { if (number>0 ) { System.out.println(Thread.currentThread().getName()+"卖出了" +(number- -)+"票,剩余:" +number); } } }
Lock 接口
实现类
什么是 “可重入” ,可重入就是说某个线程已经获得某个锁,可以再次获取锁而不会出现死锁。
ReentrantLock构造器
1 2 3 4 5 6 public ReentrantLock () { sync = new NonfairSync (); } public ReentrantLock (boolean fair) { sync = fair ? new FairSync () : new NonfairSync (); }
公平锁: 十分公平: 可以先来后到,一定要排队
非公平锁: 十分不公平,可以插队(默认)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 public class SaleTicketDemo { public static void main (String[] args) { Ticket ticket = new Ticket (); new Thread (()->{for (int i = 0 ; i < 40 ; i++) {ticket.sale();}}, "a" ).start(); new Thread (()->{for (int i = 0 ; i < 40 ; i++) ticket.sale();}, "b" ).start(); new Thread (()->{for (int i = 0 ; i < 40 ; i++) ticket.sale();}, "c" ).start(); } } class Ticket { private int ticketNum = 30 ; private Lock lock = new ReentrantLock (); public void sale () { lock.lock(); try { if (this .ticketNum > 0 ) { System.out.println(Thread.currentThread().getName() + "购得第" + ticketNum-- + "张票, 剩余" + ticketNum + "张票" ); } } finally { lock.unlock(); } } }
synchronized和lock锁的区别
synchronized内置的java关键字,Lock是一个java类
synchronized无法判断获取锁的状态, Lock可以判断是否获取到了锁
synchronized会自动释放锁,Lock必须要手动释放锁!如果不是释放锁,会产生死锁,ReentrantLock 和 synchronized 不一样,需要手动释放锁,所以使用 ReentrantLock的时候一定要手动释放锁 ,并且加锁次数和释放次数要一样
0synchronized 线程1(获得锁,阻塞),线程2(等待); Lock锁就不一定会等待下去
synchronized 可重入锁,不可以中断的,非公平的; Lock锁,可重入的,可以判断锁,非公平(可自己设置为公平锁);
synchronized 适合锁少量的代码同步问题,Lock 适合锁大量的同步代码
4.生产者和消费者问题 面试高频: 单例模式, 八大排序,生产者消费者,死锁
Synchronized实现 wait notify
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 package com.xu.PC;public class ProducerAndConsumer { public static void main (String[] args) { Resource resource = new Resource (); new Thread (()->{ for (int i = 0 ; i < 20 ; i++) { try { resource.increment(); } catch (InterruptedException e) { e.printStackTrace(); } } },"A" ).start(); new Thread (()->{ for (int i = 0 ; i < 20 ; i++) { try { resource.increment(); } catch (InterruptedException e) { e.printStackTrace(); } } },"B" ).start(); new Thread (()->{ for (int i = 0 ; i < 20 ; i++) { try { resource.decrement(); } catch (InterruptedException e) { e.printStackTrace(); } } },"C" ).start(); new Thread (()->{ for (int i = 0 ; i < 20 ; i++) { try { resource.decrement(); } catch (InterruptedException e) { e.printStackTrace(); } } },"D" ).start(); } } class Resource { private int num = 0 ; public synchronized void increment () throws InterruptedException { while (num!=0 ){ this .wait(); } num++; System.out.println(Thread.currentThread().getName()+"->" +num); this .notifyAll(); } public synchronized void decrement () throws InterruptedException { while (num == 0 ) { this .wait(); } num--; System.out.println(Thread.currentThread().getName()+"->" +num); this .notifyAll(); } }
注意:在多个线程通信时,必须使用 while 判断防止虚假唤醒。
if判断改为while判断
因为if只会执行一次,线程醒来会接着向下执行if()外边的
而while不会,会重新判断条件是否满足,满足才会向下执行while()外边的
JUC版本生产者和消费者问题
通过Lock 找到 Condition(监视者)
任何一个新的技术,绝对不是仅仅覆盖了原来的技术,一定有优势和补充
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 package com.xu.PC;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class ProducerAndConsumer2 { public static void main (String[] args) { Resource2 resource = new Resource2 (); new Thread (()->{ for (int i = 0 ; i < 20 ; i++) { try { resource.increment(); } catch (InterruptedException e) { e.printStackTrace(); } } },"A" ).start(); new Thread (()->{ for (int i = 0 ; i < 20 ; i++) { try { resource.increment(); } catch (InterruptedException e) { e.printStackTrace(); } } },"C" ).start(); new Thread (()->{ for (int i = 0 ; i < 20 ; i++) { try { resource.decrement(); } catch (InterruptedException e) { e.printStackTrace(); } } },"D" ).start(); new Thread (()->{ for (int i = 0 ; i < 20 ; i++) { try { resource.decrement(); } catch (InterruptedException e) { e.printStackTrace(); } } },"B" ).start(); } } class Resource2 { private int num = 0 ; Lock lock = new ReentrantLock (); Condition condition = lock.newCondition(); public void increment () throws InterruptedException { lock.lock(); try { while (num!=0 ){ condition.await(); } num++; System.out.println(Thread.currentThread().getName()+"->" +num); condition.signalAll(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public void decrement () throws InterruptedException { lock.lock(); try { while (num == 0 ) { condition.await(); } num--; System.out.println(Thread.currentThread().getName()+"->" +num); condition.signalAll(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } }
condition的精准通知和唤醒线程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 package com.xu.PC;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class ProducerAndConsumer3 { public static void main (String[] args) { Resource3 resource3 = new Resource3 (); new Thread (() -> { for (int i = 0 ; i < 10 ; i++) { resource3.A(); } }, "A" ).start(); new Thread (() -> { for (int i = 0 ; i < 10 ; i++) { resource3.B(); } }, "B" ).start(); new Thread (() -> { for (int i = 0 ; i < 10 ; i++) { resource3.C(); } }, "C" ).start(); } } class Resource3 { private Lock lock = new ReentrantLock (); private Condition condition1 = lock.newCondition(); private Condition condition2 = lock.newCondition(); private Condition condition3 = lock.newCondition(); private int number = 1 ; public void A () { lock.lock(); try { while (number != 1 ) { condition1.await(); } number = 2 ; System.out.println(Thread.currentThread().getName() + "->AAAAAA" ); condition2.signal(); } catch (Exception exception) { exception.printStackTrace(); } finally { lock.unlock(); } } public void B () { lock.lock(); try { while (number != 2 ) { condition2.await(); } number = 3 ; System.out.println(Thread.currentThread().getName() + "->BBBBB" ); condition3.signal(); } catch (Exception exception) { exception.printStackTrace(); } finally { lock.unlock(); } } public void C () { lock.lock(); try { while (number != 3 ) { condition3.await(); } number = 1 ; System.out.println(Thread.currentThread().getName() + "->CCCCC" ); condition1.signal(); } catch (Exception exception) { exception.printStackTrace(); } finally { lock.unlock(); } } }
5. 8锁现象 如何判断锁的是谁!永远的知道什么锁,锁到底锁的是谁!深刻理解我们的锁
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 package com.xu.LOCK;import java.util.concurrent.TimeUnit;public class Synchronized { public static void main (String[] args) { Phone phone = new Phone (); new Thread (()->{ try { phone.send(); } catch (InterruptedException e) { e.printStackTrace(); } },"t1" ).start(); try { TimeUnit.SECONDS.sleep(1 ); } catch (InterruptedException e) { e.printStackTrace(); } new Thread (()->{ phone.call(); },"t2" ).start(); } } class Phone { public synchronized void send () throws InterruptedException { System.out.println(Thread.currentThread().getName() + "sendMessage" ); TimeUnit.SECONDS.sleep(2 ); call(); } public synchronized void call () { System.out.println(Thread.currentThread().getName() + "call" ); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 package com.czp.lock;import java.util.concurrent.TimeUnit;public class Test2 { public static void main (String[] args) { Phone1 phone = new Phone1 (); Phone1 phone2 = new Phone1 (); new Thread (() -> { phone.sendMessage(); }, "A" ).start(); try { TimeUnit.SECONDS.sleep(1 ); } catch (InterruptedException e) { e.printStackTrace(); } new Thread (() -> { phone2.call(); }, "B" ).start(); } } class Phone1 { public synchronized void sendMessage () { try { TimeUnit.SECONDS.sleep(4 ); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "sendMessage" ); } public synchronized void call () { System.out.println(Thread.currentThread().getName() + "call" ); } public void hello () { System.out.println("hello" ); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 package com.czp.lock;import java.util.concurrent.TimeUnit;public class Test3 { public static void main (String[] args) { Phone2 phone2 = new Phone2 (); Phone2 phone3 = new Phone2 (); new Thread (() -> { phone2.sendMessage(); }, "A" ).start(); try { TimeUnit.SECONDS.sleep(1 ); } catch (InterruptedException e) { e.printStackTrace(); } new Thread (() -> { phone3.call(); }, "B" ).start(); } } class Phone2 { public static synchronized void sendMessage () { try { TimeUnit.SECONDS.sleep(4 ); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "sendMessage" ); } public static synchronized void call () { System.out.println(Thread.currentThread().getName() + "call" ); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 package com.czp.lock;import java.util.concurrent.TimeUnit;public class Test4 { public static void main (String[] args) { Phone3 phone3 = new Phone3 (); Phone3 phone4 = new Phone3 (); new Thread (() -> { phone3.sendMessage(); }, "A" ).start(); try { TimeUnit.SECONDS.sleep(1 ); } catch (InterruptedException e) { e.printStackTrace(); } new Thread (() -> { phone4.call(); }, "B" ).start(); } } class Phone3 { public static synchronized void sendMessage () { try { TimeUnit.SECONDS.sleep(4 ); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "sendMessage" ); } public synchronized void call () { System.out.println(Thread.currentThread().getName() + "call" ); } }
小结:
synchronized 方法锁的是调用者 this 具体的一个手机
static 方法锁的是模板 Class 唯一的一个模板
6.集合类不安全 list 不安全 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 public class ListTest { public static void main (String[] args) { List<String> arrayList = new CopyOnWriteArrayList <>(); for (int i = 0 ; i < 100 ; i++) { new Thread (()->{ arrayList.add(UUID.randomUUID().toString().substring(0 ,5 )); System.out.println(arrayList); },String.valueOf(i)).start(); } } }
Set 不安全 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 public class SetTest { public static void main (String[] args) { Set<String> set = new CopyOnWriteArraySet <>(); for (int i = 0 ; i < 100 ; i++) { new Thread (() -> { set.add(UUID.randomUUID().toString().substring(0 , 5 )); System.out.println(set); }, String.valueOf(i)).start(); } } }
hashSet底层是什么? hashMap
1 2 3 4 5 6 7 8 9 10 public HashSet () { map = new HashMap <>(); } public boolean add (E e) { return map.put(e, PRESENT)==null ; } private static final Object PRESENT = new Object ();
HashMap 不安全 回顾Map基本操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 package com.kuang.unsafe;import java.util.Collections; import java.util.HashMap; import java.util.Map;import java.util.UUID;import java.util.concurrent.ConcurrentHashMap;public class MapTest { public static void main (String[] args) { Map<String, String> map = new ConcurrentHashMap <>(); for (int i = 1 ; i <=30 ; i++) { new Thread (()->{ map.put(Thread.currentThread().getName(),UUID.randomUUID().toString().substring( 0 ,5 )); System.out.println(map); },String.valueOf(i)).start(); } } }
7. Callable()
可以有返回值
可以抛出异常
方法不同, run() => call()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 package com.kuang.callable;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask;import java.util.concurrent.locks.ReentrantLock;public class CallableTest { public static void main (String[] args) throws ExecutionException, InterruptedException { MyThread thread = new MyThread (); FutureTask futureTask = new FutureTask (thread); new Thread (futureTask,"A" ).start(); new Thread (futureTask,"B" ).start(); Integer o = (Integer) futureTask.get(); System.out.println(o); } } class MyThread implements Callable <Integer> { @Override public Integer call () { System.out.println("call()" ); return 1024 ; } }
细节:
1、有缓存 2、结果可能需要等待,会阻塞!
8. 常用的辅助类 CountDownLatch
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 public class CountDownLatchDemo { public static void main (String[] args) throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch (6 ); for (int i = 0 ; i < 6 ; i++) { new Thread (()->{ System.out.println(Thread.currentThread().getName() + " GO out" ); countDownLatch.countDown(); },String.valueOf(i)).start(); } countDownLatch.await(); System.out.println("close Door" ); } }
原理:
countDownLatch.countDown(); //数量减1
countDownLatch.await();// 等待计数器归零,然后再向下执行
每次有线程调用countDown()数量-1,计数器变为0, countDownLatch.await();就会被唤醒,继续执行
CyclicBarrier
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 package com.xu.Others;import java.util.concurrent.BrokenBarrierException;import java.util.concurrent.CyclicBarrier;public class TestCyclicBarrier { public static void main (String[] args) { CyclicBarrier cyclicBarrier = new CyclicBarrier (7 , () -> { System.out.println("集齐七颗龙珠召唤神龙" ); }); for (int i = 1 ; i <= 7 ; i++) { final int temp = i; new Thread (()->{ System.out.println(Thread.currentThread().getName() + "集齐了第" + temp + "个龙珠" ); try { cyclicBarrier.await(); System.out.println("ok" ); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } }).start(); } } }
Semaphore Semaphore:信号量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 package com.xu.Others;import java.util.concurrent.Semaphore;import java.util.concurrent.TimeUnit;public class TestSemaphore { public static void main (String[] args) { Semaphore semaphore = new Semaphore (3 ); for (int i = 1 ; i <= 6 ; i++) { new Thread (() -> { try { System.out.println("ok" ); semaphore.acquire(); System.out.println(Thread.currentThread().getName() + "抢到了车位" ); TimeUnit.SECONDS.sleep(2 ); System.out.println(Thread.currentThread().getName() + "离开了车位" ); } catch (InterruptedException e) { e.printStackTrace(); } finally { semaphore.release(); } },String.valueOf(i)).start(); } } }
原理:
semaphore.acquire(); //获取信号量,假设如果已经满了,等待信号量可用时被唤醒
semaphore.release(); //释放信号量
作用: 多个共享资源互斥的使用!并发限流,控制最大的线程数
9.读写锁 ReadWriteLock
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 package com.xu.WriteAndRead;import java.util.HashMap;import java.util.Map;import java.util.concurrent.locks.ReadWriteLock;import java.util.concurrent.locks.ReentrantReadWriteLock;public class Test { public static void main (String[] args) { Mycache2 mycache = new Mycache2 (); for (int i = 1 ; i <= 10 ; i++) { final int temp = i; new Thread (() -> { mycache.write(temp + "" , temp + "" ); }, String.valueOf(i)).start(); } for (int i = 1 ; i <= 10 ; i++) { final int temp = i; new Thread (() -> { mycache.read(temp + "" ); }, String.valueOf(i)).start(); } } } class Mycache2 { private volatile Map<String, String> map = new HashMap <>(); private ReadWriteLock readWriteLock = new ReentrantReadWriteLock (); public void write (String key, String value) { readWriteLock.writeLock().lock(); try { System.out.println(Thread.currentThread().getName() + "写" ); map.put(key, value); System.out.println(Thread.currentThread().getName() + "写OK" ); } finally { readWriteLock.writeLock().unlock(); } } public void read (String key) { readWriteLock.readLock().lock(); try { System.out.println(Thread.currentThread().getName() + "读" ); map.get(key); System.out.println(Thread.currentThread().getName() + "读OK" ); } finally { readWriteLock.readLock().unlock(); } } } class Mycache { private volatile Map<String, String> map = new HashMap <>(); public void write (String key, String value) { System.out.println(Thread.currentThread().getName() + "写" ); map.put(key, value); System.out.println(Thread.currentThread().getName() + "写OK" ); } public void read (String key) { System.out.println(Thread.currentThread().getName() + "读" ); map.get(key); System.out.println(Thread.currentThread().getName() + "读OK" ); } }
10.阻塞队列
阻塞队列
Blockqueue
什么情况下我们会使用阻塞队列? 多线程并发处理,线程池!
学会使用队列
添加,移除
四组API
方式
抛出异常
不会抛出异常,有返回值
阻塞等待
超时等待
添加操作
add()
offer() 供应
put()
offer(obj,int,timeunit.status)
移除操作
remove()
poll() 获得
take()
poll(int,timeunit.status)
判断队列首部
element()
peek() 偷看,偷窥
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 package com.xu.Queue;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.TimeUnit;public class testBlockingQueue { public static void main (String[] args) throws InterruptedException { test4(); } public static void test4 () throws InterruptedException { ArrayBlockingQueue<Object> arrayBlockingQueue4 = new ArrayBlockingQueue <>(3 ); System.out.println(arrayBlockingQueue4.offer("a" )); System.out.println(arrayBlockingQueue4.offer("b" )); System.out.println(arrayBlockingQueue4.offer("c" )); System.out.println(arrayBlockingQueue4.offer("d" ,2 , TimeUnit.SECONDS)); System.out.println("_____________" ); System.out.println(arrayBlockingQueue4.poll()); System.out.println(arrayBlockingQueue4.poll()); System.out.println(arrayBlockingQueue4.poll()); System.out.println(arrayBlockingQueue4.poll(2 ,TimeUnit.SECONDS)); } public static void test3 () throws InterruptedException { ArrayBlockingQueue<Object> arrayBlockingQueue3 = new ArrayBlockingQueue <>(3 ); arrayBlockingQueue3.put("a" ); arrayBlockingQueue3.put("b" ); arrayBlockingQueue3.put("c" ); System.out.println("_____________" ); System.out.println(arrayBlockingQueue3.take()); System.out.println(arrayBlockingQueue3.take()); System.out.println(arrayBlockingQueue3.take()); } public static void test2 () { ArrayBlockingQueue<Object> arrayBlockingQueue2 = new ArrayBlockingQueue <>(3 ); System.out.println(arrayBlockingQueue2.offer("a" )); System.out.println(arrayBlockingQueue2.offer("b" )); System.out.println(arrayBlockingQueue2.offer("c" )); System.out.println(arrayBlockingQueue2.offer("d" )); System.out.println("_____________" ); System.out.println(arrayBlockingQueue2.poll()); System.out.println(arrayBlockingQueue2.poll()); System.out.println(arrayBlockingQueue2.poll()); System.out.println(arrayBlockingQueue2.poll()); } public static void test () { ArrayBlockingQueue<Object> arrayBlockingQueue = new ArrayBlockingQueue <>(3 ); System.out.println(arrayBlockingQueue.add("a" )); System.out.println(arrayBlockingQueue.add("b" )); System.out.println(arrayBlockingQueue.add("c" )); System.out.println("_____________" ); System.out.println(arrayBlockingQueue.remove("b" )); System.out.println(arrayBlockingQueue.remove()); System.out.println(arrayBlockingQueue.remove()); } }
SynchronizedQueue 同步队列
没有容量,
进去一个元素,必须等待取出来之后,才能再往里面放一个元素
put take
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 public class SyncQueue { public static void main (String[] args) { SynchronousQueue<String> synchronousQueue = new SynchronousQueue <>(); new Thread (()->{ try { System.out.println(Thread.currentThread().getName() + "put 1" ); synchronousQueue.put("1" ); System.out.println(Thread.currentThread().getName() + "put 2" ); synchronousQueue.put("2" ); System.out.println(Thread.currentThread().getName() + "put 3" ); synchronousQueue.put("3" ); } catch (InterruptedException e) { e.printStackTrace(); } },"T1" ).start(); new Thread (()->{ try { TimeUnit.SECONDS.sleep(3 ); System.out.println(Thread.currentThread().getName() + "=>" + synchronousQueue.take()); TimeUnit.SECONDS.sleep(3 ); System.out.println(Thread.currentThread().getName() + "=>" + synchronousQueue.take()); TimeUnit.SECONDS.sleep(3 ); System.out.println(Thread.currentThread().getName() + "=>" + synchronousQueue.take()); } catch (InterruptedException e) { e.printStackTrace(); } finally { } },"T2" ).start(); } }
11.线程池 线程池: 三大方法,七大参数,4种拒绝策略
池化技术
程序的运行,本质:占用系统的资源! 优化资源的使用!=>池化技术
线程池、连接池、内存池、对象池///. 创建、销毁。十分浪费资源
池化技术:事先准备好一些资源,有人要用,就来我这里拿,用完之后还给我。
线程池的好处:
1、降低资源的消耗
2、提高响应的速度
3、方便管理。
线程复用、可以控制最大并发数、管理线程
线程池: 三大方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public class Demo01 { public static void main (String[] args) { ExecutorService service = Executors.newCachedThreadPool(); try { for (int i = 0 ; i < 10 ; i++) { service.execute(() -> { System.out.println(Thread.currentThread().getName() + "ok" ); }); } } finally { service.shutdown(); } } }
7大参数 newSingleThreadExecutor构造器
1 2 3 4 5 6 public static ExecutorService newSingleThreadExecutor () { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor (1 , 1 , 0L , TimeUnit.MILLISECONDS, new LinkedBlockingQueue <Runnable>())); }
newFixedThreadPool构造器
1 2 3 4 5 public static ExecutorService newFixedThreadPool (int nThreads) { return new ThreadPoolExecutor (nThreads, nThreads, 0L , TimeUnit.MILLISECONDS, new LinkedBlockingQueue <Runnable>()); }
newCachedThreadPool构造器
1 2 3 4 5 public static ExecutorService newCachedThreadPool () { return new ThreadPoolExecutor (0 , Integer.MAX_VALUE, 60L , TimeUnit.SECONDS, new SynchronousQueue <Runnable>()); }
本质: 所有线程池最终都调用的ThreadPoolExecutor
ThreadPoolExecutor底层构造器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 public ThreadPoolExecutor (int corePoolSize, //核心线程池大小 int maximumPoolSize, //最大的线程池大小 long keepAliveTime, // 超时了没有人调用就会释放 TimeUnit unit, //时间单位 BlockingQueue<Runnable> workQueue, //阻塞队列 ThreadFactory threadFactory,//线程工厂,创建线程的,一般不动 RejectedExecutionHandler handler) { if (corePoolSize < 0 || maximumPoolSize <= 0 || maximumPoolSize < corePoolSize || keepAliveTime < 0 ) throw new IllegalArgumentException (); if (workQueue == null || threadFactory == null || handler == null ) throw new NullPointerException (); this .acc = System.getSecurityManager() == null ? null : AccessController.getContext(); this .corePoolSize = corePoolSize; this .maximumPoolSize = maximumPoolSize; this .workQueue = workQueue; this .keepAliveTime = unit.toNanos(keepAliveTime); this .threadFactory = threadFactory; this .handler = handler; }
手动创建线程池
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 package com.xu.Pool;import java.util.concurrent.*;public class testThreadPoolExecutor { public static void main (String[] args) { ExecutorService threadPoolExecutor = new ThreadPoolExecutor ( 2 , 4 , 3 , TimeUnit.SECONDS, new ArrayBlockingQueue <>(6 ), Executors.defaultThreadFactory(), new ThreadPoolExecutor .DiscardOldestPolicy() ); try { for (int i = 0 ; i <12 ; i++) { threadPoolExecutor.execute(() -> { System.out.println(Thread.currentThread().getName() + "run" ); }); } } catch (Exception exception) { exception.printStackTrace(); } finally { threadPoolExecutor.shutdown(); } } }
四种拒绝策略
小结和扩展
了解:最大线程到底应该如何定义
CPU密集型 几核,就是几,可以保证CPU的效率最高
IO 密集型 判断程序中十分耗I/O的线程, 大于两倍
1 2 System.out.println(Runtime.getRuntime().availableProcessors());
12.四大函数式接口 新时代的程序员:lambda表达式、链式编程、函数式接口、Stream流式计算
函数式接口:只有一个方法的接口
1 2 3 4 5 6 7 8 9 @FunctionalInterface public interface Runnable { public abstract void run () ; }
Function函数式接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 package com.kuang.function;import java.util.function.Function;public class Demo01 { public static void main (String[] args) { Function<String,String> function = (str)->{return str;}; System.out.println(function.apply("asd" )); } }
Predicate 断定型接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 package com.kuang.function;import java.util.function.Predicate;public class Demo02 { public static void main (String[] args) { Predicate<String> predicate = (str)->{return str.isEmpty(); }; System.out.println(predicate.test("" )); } }
Consumer 消费型接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 package com.kuang.function;import java.util.function.Consumer;public class Demo03 { public static void main (String[] args) { Consumer<String> consumer = (str)->{System.out.println(str);}; consumer.accept("sdadasd" ); } }
Supplier 供给型接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 package com.kuang.function;import java.util.function.Supplier;public class Demo04 { public static void main (String[] args) { Supplier supplier = ()->{ return 1024 ; }; System.out.println(supplier.get()); } }
13.Stream 流式计算
什么是流式计算
大数据:存储 + 计算
集合、MySQL 本质就是存储东西的; 计算都应该交给流来操作!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 package com.kuang.stream;import java.util.Arrays; import java.util.List;public class Test { public static void main (String[] args) { User u1 = new User (1 ,"a" ,21 ); User u2 = new User (2 ,"b" ,22 ); User u3 = new User (3 ,"c" ,23 ); User u4 = new User (4 ,"d" ,24 ); User u5 = new User (6 ,"e" ,25 ); List<User> list = Arrays.asList(u1, u2, u3, u4, u5); list.stream() .filter(u->{return u.getId()%2 ==0 ;}) .filter(u->{return u.getAge()>23 ;}) .map(u->{return u.getName().toUpperCase();}) .sorted((uu1,uu2)->{return uu2.compareTo(uu1);}) .limit(1 ) .forEach(System.out::println); } }
14. ForkJoin
什么是ForkJoin
ForkJoin在JDK1.7,并行执行任务,大数据量!
大数据: Map Reduce( 把大任务拆分成小任务)
ForkJoin特点: 工作窃取
这个里面维护的是一个双端队列
ForkJoin
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 package com.kuang.forkjoin;import java.util.concurrent.RecursiveTask;public class ForkJoinDemo extends RecursiveTask <Long> { private Long start; private Long end; private Long temp = 10000L ; public ForkJoinDemo (Long start, Long end) { this .start = start; this .end = end; } @Override protected Long compute () { if ((end-start)<temp){ Long sum = 0L ; for (Long i = start; i <= end; i++) { sum += i; } return sum; }else { long middle = (start + end) / 2 ; ForkJoinDemo task1 = new ForkJoinDemo (start, middle); task1.fork(); ForkJoinDemo task2 = new ForkJoinDemo (middle+1 , end); task2.fork(); return task1.join() + task2.join(); } } }
测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 package com.xu.ForkJoin;import java.util.concurrent.ExecutionException;import java.util.concurrent.ForkJoinPool;import java.util.concurrent.ForkJoinTask;import java.util.stream.LongStream;public class test { public static void main (String[] args) throws ExecutionException, InterruptedException { test3(); } public static void test1 () { long start = System.currentTimeMillis(); long sum = 0l ; for (long i = 0l ; i <=10_0000_0000l ; i++) { sum+=i; } long end = System.currentTimeMillis(); System.out.println("sum=" +sum+"运行时间;" +(end-start)); } public static void test2 () throws ExecutionException, InterruptedException { long start = System.currentTimeMillis(); Long sum; ForkJoinPool forkJoinPool = new ForkJoinPool (); forkjoinDemo forkjoinDemo = new forkjoinDemo (0l , 10_0000_0000l ); ForkJoinTask<Long> task = forkJoinPool.submit(forkjoinDemo); sum = task.get(); long end = System.currentTimeMillis(); System.out.println("sum=" +sum+"运行时间;" +(end-start)); } public static void test3 () { long start = System.currentTimeMillis(); long sum = LongStream.rangeClosed(0l , 10_0000_0000l ).parallel().reduce(1 , Long::sum); long end = System.currentTimeMillis(); System.out.println("sum=" +sum+"运行时间;" +(end-start)); } }
15. 异步回调
Future设计的初衷: 对将来的某个事件的结果进行建模
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 package com.xu.CompletableFutrue;import java.util.concurrent.CompletableFuture;import java.util.concurrent.ExecutionException;public class test { public static void main (String[] args) throws ExecutionException, InterruptedException { CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(()->{ System.out.println(Thread.currentThread().getName() + "run" ); int i = 10 /0 ; return 1024 ; }); System.out.println(completableFuture.whenComplete((u, t) -> { System.out.println("u=" + u); System.out.println("t=" + t); }).exceptionally((e) -> { System.out.println(e.getMessage()); return 111 ; }).get()); } }
16.JMM
请你谈谈你对Volate的理解
Volate是java虚拟机提供轻量级的同步机制
JMM是什么
JMM: java内存模型,不存在的东西,概念!约定!
关于JMM的一些同步的约定:
线程解锁前,必须把共享变量立刻 刷回主存
线程加锁前,必须读取主存中的最新值到工作内存中!
加锁和解锁必须是同一把锁
线程 工作内存 主内存
8种操作:(这里的 write 和 store 交换位置)
操作
说明
lock (锁定)
作用于主内存的变量,把一个变量标识为线程独占状态
unlock (解锁)
作用于主内存的变量,它把一个处于锁定状态的变量释放出来,释放后的变量才可以被其他线程锁定
read (读取)
作用于主内存变量,它把一个变量的值从主内存传输到线程的工作内存中,以便随后的load动作使用
load (载入)
作用于工作内存的变量,它把read操作从主存中变量放入工作内存中
use (使用)
作用于工作内存中的变量,它把工作内存中的变量传输给执行引擎,每当虚拟机遇到一个需要使用到变量的值,就会使用到这个指令
assign (赋值)
作用于工作内存中的变量,它把一个从执行引擎中接受到的值放入工作内存的变量副本中
store (存储)
作用于主内存中的变量,它把一个从工作内存中一个变量的值传送到主内存中,以便后续的write使用
write (写入)
作用于主内存中的变量,它把store操作从工作内存中得到的变量的值放入主内存的变量中
八种规则 :
不允许read和load、store和write操作之一单独出现。即使用了read必须load,使用了store必须write
不允许线程丢弃他最近的assign操作,即工作变量的数据改变了之后,必须告知主存
不允许一个线程将没有assign的数据从工作内存同步回主内存
一个新的变量必须在主内存中诞生,不允许工作内存直接使用一个未被初始化的变量。就是对变量实施use、store操作之前,必须经过assign和load操作
一个变量同一时间只有一个线程能对其进行lock。多次lock后,必须执行相同次数的unlock才能解锁
如果对一个变量进行lock操作,会清空所有工作内存中此变量的值,在执行引擎使用这个变量前,必须重新load或assign操作初始化变量的值
如果一个变量没有被lock,就不能对其进行unlock操作。也不能unlock一个被其他线程锁住的变量
对一个变量进行unlock操作之前,必须把此变量同步回主内存
问题: 程序不知道主内存中的值已经被修改过了
17. Volatile 保证可见性 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 public class JMMDemo { private volatile static int number = 0 ; public static void main (String[] args) { new Thread (()->{ while (number == 0 ){ } }).start(); try { TimeUnit.SECONDS.sleep(2 ); } catch (InterruptedException e) { e.printStackTrace(); } finally { } number = 1 ; System.out.println(number); } }
不保证原子性 原子性: 不可分割
线程A在执行任务的时候.不能被打扰,也不能被分割,要么同时成功,要么同时失败
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 public class VDemo { private volatile static int num = 0 ; public static void add () { num++; } public static void main (String[] args) { for (int i = 0 ; i < 20 ; i++) { new Thread (()->{ for (int j = 0 ; j < 1000 ; j++) { add(); } }).start(); } while (Thread.activeCount() > 2 ){ Thread.yield (); } System.out.println(num); } }
如果不加lock和synchronized,如何保证原子性
使用原子类,解决原子性问题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 public class VDemo { private volatile static AtomicInteger num = new AtomicInteger (0 ); public static void add () { num.getAndIncrement(); } public static void main (String[] args) { for (int i = 0 ; i < 20 ; i++) { new Thread (()->{ for (int j = 0 ; j < 1000 ; j++) { add(); } }).start(); } while (Thread.activeCount() > 2 ){ Thread.yield (); } System.out.println(num); } }
这些类的底层都直接和操作系统挂钩 ! 在内存中修改值! UnSafe类是一个很特殊的存在
指令重排
什么是指令重排: 你写的程序,计算机并不是按照指定的的步骤执行
源代码—>编译器优化源代码–>指令并行也可能会重排—>内存系统也会重排执行
处理器在进行指令重排的时候,考虑:数据之间的依赖性!
1 2 3 4 5 6 7 int x = 1 ; int y = 2 ; x = x + 5 ; y = x * x; 我们所期望的:1234 但是可能执行的时候回变成 2134 1324 可不可能是 4123 !
可能造成影响的结果: a b x y 这四个值默认都是 0;
正常的结果: x = 0;y = 0;但是可能由于指令重排
指令重排导致的诡异结果: x = 2;y = 1;
volatile 可以避免指令重排 :
内存屏障。CPU指令。作用:
1、保证特定的操作的执行顺序!
2、可以保证某些变量的内存可见性 (利用这些特性volatile实现了可见性)
Volatile 是可以保证可见性, 不能保证原子性,由于内存屏障可以避免指令重排的现象产生 !
18.单例模式 饿汉模式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 package com.kuang.single;public class Hungry { private Hungry () { } private final static Hungry HUNGRY = new Hungry (); public static Hungry getInstance () { return HUNGRY; } }
懒汉模式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 package com.czp.single;public class LazyMan { private static LazyMan lazyMan = null ; private LazyMan () { } public static LazyMan getInstance () { if (lazyMan == null ){ lazyMan = new LazyMan (); } return lazyMan; } }
DCL 懒汉式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 package com.czp.single;import java.lang.reflect.Constructor;public class LazyManThread { private static volatile LazyManThread lazyManThread = null ; private static boolean isExist = false ; private LazyManThread () { synchronized (LazyManThread.class) { if (!isExist) { isExist = true ; } else { throw new RuntimeException ("禁止使用反射创建该对象" ); } } } public static LazyManThread getInstance () { if (lazyManThread == null ) { synchronized (LazyManThread.class) { if (lazyManThread == null ) { lazyManThread = new LazyManThread (); } } } return lazyManThread; } public static void main (String[] args) throws Exception { Constructor<LazyManThread> declaredConstructor = LazyManThread.class.getDeclaredConstructor(); declaredConstructor.setAccessible(true ); LazyManThread lazyManThread = declaredConstructor.newInstance(); LazyManThread instance = declaredConstructor.newInstance(); System.out.println(instance); System.out.println(lazyManThread); } }
静态内部类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public class LazyMan1 { private LazyMan1 () {} public static final LazyMan1 getInstance () { return innerClass.LAZY_MAN_1; } public static class innerClass { private static final LazyMan1 LAZY_MAN_1 = new LazyMan1 (); } }
单例不安全,反射 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 package com.xu.SingleInstance;import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException;public class LazyMan { private volatile static LazyMan lazyMan; private LazyMan () { System.out.println("new lazyman()" ); } public static LazyMan getLazyMan () { if (lazyMan == null ) { synchronized (LazyMan.class) { if (lazyMan == null ) { lazyMan = new LazyMan (); } } } return lazyMan; } public static void main (String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null ); declaredConstructor.setAccessible(true ); LazyMan lazyMan1 = declaredConstructor.newInstance(); LazyMan lazyMan2 = declaredConstructor.newInstance(); System.out.println(lazyMan2); System.out.println(lazyMan1); } }
枚举 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 package com.xu.SingleInstance;import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException;public class Enum { public static void main (String[] args) throws InterruptedException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Constructor<instance> constructor = Instance.class.getDeclaredConstructor(String.class,int .class); Constructor<instance> constructor = Instance.class.getDeclaredConstructor(String.class,int .class,String.class); constructor.setAccessible(true ); Instance instance = constructor.newInstance(); } } public enum Instance { ; private String name; Instance(){ } Instance(String name){ this .name = name; } }
下面是探究枚举类构造函数,以及反编译枚举类的源码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 package com.kuang.single;import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException;public enum EnumSingle { INSTANCE; public EnumSingle getInstance () { return INSTANCE; } } class Test { public static void main (String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { EnumSingle instance1 = EnumSingle.INSTANCE; Constructor<EnumSingle> declaredConstructor = EnumSingle.class.getDeclaredConstructor(String.class,int .class); declaredConstructor.setAccessible(true ); EnumSingle instance2 = declaredConstructor.newInstance(); System.out.println(instance2); }
枚举类型的最终反编译源码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 package com.kuang.single;public final class EnumSingle extends Enum { public static EnumSingle[] values() { return (EnumSingle[])$VALUES.clone(); } public static EnumSingle valueOf (String name) { return (EnumSingle)Enum.valueOf(com/kuang/single/EnumSingle, name); } private EnumSingle (String s, int i) { super (s, i); } public EnumSingle getInstance () { return INSTANCE; } public static final EnumSingle INSTANCE; private static final EnumSingle $VALUES[]; static { INSTANCE = new EnumSingle ("INSTANCE" , 0 ); $VALUES = (new EnumSingle [] { INSTANCE }); } }
19.深入理解CAS 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 package com.kuang.cas;import java.util.concurrent.atomic.AtomicInteger;public class CASDemo { public static void main (String[] args) { AtomicInteger atomicInteger = new AtomicInteger (1 ); System.out.println(atomicInteger.compareAndSet(1 , 2 )); System.out.println(atomicInteger.get()); System.out.println(atomicInteger.getAndIncrement()); System.out.println(atomicInteger.get()); System.out.println(atomicInteger.compareAndSet(1 , 2 )); System.out.println(atomicInteger.get()); } }
Unsafe 类
CAS : 比较当前工作内存中的值和主内存中的值,如果这个值是期望的,那么则执行操作!如果不是就一直循环!
缺点:
1、 循环会耗时 2、一次性只能保证一个共享变量的原子性 3、ABA问题
CAS:ABA问题(狸猫换太子)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 package com.kuang.cas;import java.util.concurrent.atomic.AtomicInteger;public class CASDemo { public static void main (String[] args) { AtomicInteger atomicInteger = new AtomicInteger (2020 ); System.out.println(atomicInteger.compareAndSet(2020 , 2021 )); System.out.println(atomicInteger.get()); System.out.println(atomicInteger.compareAndSet(2021 , 2020 )); System.out.println(atomicInteger.get()); System.out.println(atomicInteger.compareAndSet(2020 , 6666 )); System.out.println(atomicInteger.get()); } }
20 . 原子引用
解决ABA问题, 引入原子引用 ! 对应的思想: 乐观锁
带版本号的原子操作 !
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 package com.xu.CASdemo;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicStampedReference;public class AtomicStampedReferenceDemo { public static void main (String[] args) { AtomicStampedReference<Long> atomicStampedReference = new AtomicStampedReference (1L , 1 ); new Thread (()->{ System.out.println("a1->" +atomicStampedReference.getStamp()); try { TimeUnit.SECONDS.sleep(1 ); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(atomicStampedReference.compareAndSet(1L , 2L , atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1 )); System.out.println("a2->" + atomicStampedReference.getStamp()); System.out.println(atomicStampedReference.compareAndSet(2L , 1L , atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1 )); System.out.println("a3->" + atomicStampedReference.getStamp()); },"a" ).start(); new Thread (()->{ int stamp = atomicStampedReference.getStamp(); System.out.println("b1->" +stamp); try { TimeUnit.SECONDS.sleep(2 ); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(atomicStampedReference.compareAndSet(1L , 6L ,stamp, stamp+ 1 )); System.out.println("b2->" +atomicStampedReference.getStamp()); },"b" ).start(); } }
注意:Integer 使用了对象缓存机制,默认范围是-128~127,推荐使用静态工厂的方法valueOf 获取对象实例,而不是new,因为valueOf 使用缓存,而new一定会创建新的对象分配新的内存空间;
21.各种锁的理解 公平锁, 非公平锁 公平锁: 非常公平,先来后到,不允许插队
非公平锁: 非常不公平, 允许插队
1 2 3 4 5 6 public ReentrantLock () { sync = new NonfairSync (); } public ReentrantLock (boolean fair) { sync = fair ? new FairSync () : new NonfairSync (); }
可重入锁 ( 递归锁 ) 释义: 可重入锁指的是可重复可递归调用的锁,在外层使用锁之后,在内层仍然可以使用,并且不发生死锁(前提得是同一个对象或者class),这样的锁就叫做可重入锁
synchronized版本的可重入锁
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 public class TestLock { public static void main (String[] args) { TestPhone phone = new TestPhone (); new Thread (()->{ phone.sendMessage(); }).start(); } } class TestPhone { public synchronized void sendMessage () { System.out.println(Thread.currentThread().getName() + "sendMessage" ); call(); } public synchronized void call () { System.out.println(Thread.currentThread().getName() + "call" ); } }
Lock版本的可重入锁
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 package com.kuang.lock;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class Demo02 { public static void main (String[] args) { Phone2 phone = new Phone2 (); new Thread (()->{ phone.sms(); },"A" ).start(); new Thread (()->{ phone.sms(); },"B" ).start(); } } class Phone2 { Lock lock = new ReentrantLock (); public void sms () { lock.lock(); lock.lock(); try { System.out.println(Thread.currentThread().getName() + "sms" ); call(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); lock.unlock(); } } public void call () { lock.lock(); try { System.out.println(Thread.currentThread().getName() + "call" ); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } }
自旋锁
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 package com.xu.LOCK;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicReference;public class Spinlock { public static void main (String[] args) throws InterruptedException { Mylock mylock = new Mylock (); new Thread (()->{ mylock.lock(); try { System.out.println("a" ); TimeUnit.SECONDS.sleep(5 ); } catch (Exception e) { e.printStackTrace(); } finally { mylock.unlock(); } },"A" ).start(); TimeUnit.SECONDS.sleep(1 ); new Thread (()->{ mylock.lock(); try { System.out.println("b" ); TimeUnit.SECONDS.sleep(6 ); } catch (Exception e) { e.printStackTrace(); } finally { mylock.unlock(); } },"B" ).start(); } } class Mylock { AtomicReference<Thread> atomicReference = new AtomicReference <>(); public void lock () { Thread thread = Thread.currentThread(); while (!atomicReference.compareAndSet(null , thread)) { System.out.println(thread.getName()+"->b" ); } System.out.println(thread.getName()+"->lock" ); } public void unlock () { Thread thread = Thread.currentThread(); System.out.println(thread.getName() + "->unlock" ); atomicReference.compareAndSet(thread, null ); } }
死锁 产生死锁的四大条件:互斥、占有等待、循环等待、不可抢占(破坏其中一个就不会产生死锁)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 package com.czp.lock;import java.util.concurrent.TimeUnit;public class KillLock implements Runnable { private String stringA; private String stringB; public KillLock (String stringA, String stringB) { this .stringA = stringA; this .stringB = stringB; } @Override public void run () { synchronized (stringA) { System.out.println(Thread.currentThread().getName() + "lock" + stringA + "try to lock stringB" ); try { TimeUnit.SECONDS.sleep(2 ); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (stringB) { System.out.println(Thread.currentThread().getName() + "lock" + stringB + "try to lock stringA" ); } } } public static void main (String[] args) { String a = "a" ; String b = "b" ; new Thread (new KillLock (a, b)).start(); new Thread (new KillLock (b, a)).start(); } }
如何排查死锁
先使用jps -l定位进程号
再使用 jstack 查看进程信息找到死锁问题
面试,工作中! 排查问题:
1、日志 9
2、堆栈 1