文章目录
- 1.什么是Juc?
- 2.Lock?
- 3.进程和线程的区别?
- 4.线程的状态
- 5.Lock锁的详细讲解(important)
- 6.生产者消费者sychronized版本
- 7.生产者消费者Lock版本
- 8.防止虚假唤醒把其中的if变为while实现
- 9.Condition可以做到精准通知和唤醒线程 也就是可以让线程有序的执行
- 10.集合的线程安全类CopyOnWriteArrayList,底层通过Lock接口实现线程的安全
- 10.集合的线程安全类CopyWriteOnArraySet
- 11.Callable实现多线程
- 12.并发实现的常用辅助类
- 13.ReadWriteLock的实现
- 14.BlockingQueue阻塞队列实现线程的几种方式
- 15池化技术和线程池的使用
- 16 CAS(Compare and Set)
1.什么是Juc?
JUI的并发编程
业务:普通的线程代码类Thread, Runnable接口,没有返回值,相比Callable效率低,所以企业的开发中使用Callable接口多.
2.Lock?
java.util.current.Lock 包括ReetrantLock,ReetrantReadWriteLock
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nkbEAuMH-1639027859900)(C:\Users\CourageAndLove\AppData\Roaming\Typora\typora-user-images\image-20211207134110414.png)]
3.进程和线程的区别?
进程:一个程序 QQ.exe,.jar,包含多个线程
一个java程序默认几个线程?2个
java真的可以开启线程吗?不可以,看它的方法知道它只可以通过调用start0方法操作,底层通过c++来进行操作硬件。
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0)
throw new IllegalThreadStateException();
/* Notify the group that this thread is about to be started
* so that it can be added to the group's list of threads
* and the group's unstarted count can be decremented. */
group.add(this);
boolean started = false;
try {
start0();
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}
private native void start0();
并发并行的区别?
并发多个线程操作同一资源。
并行:cpu多核,多个线程同时执行
JUC并发编程的目的:充分利用CPU的资源。
4.线程的状态
线程的状态源码
public enum State {
/**
* Thread state for a thread which has not yet started.
*/
//
NEW,
/**
* Thread state for a runnable thread. A thread in the runnable
* state is executing in the Java virtual machine but it may
* be waiting for other resources from the operating system
* such as processor.
*/
RUNNABLE,
/**
* Thread state for a thread blocked waiting for a monitor lock.
* A thread in the blocked state is waiting for a monitor lock
* to enter a synchronized block/method or
* reenter a synchronized block/method after calling
* {@link Object#wait() Object.wait}.
*/
BLOCKED,
/**
* Thread state for a waiting thread.
* A thread is in the waiting state due to calling one of the
* following methods:
* <ul>
* <li>{@link Object#wait() Object.wait} with no timeout</li>
* <li>{@link #join() Thread.join} with no timeout</li>
* <li>{@link LockSupport#park() LockSupport.park}</li>
* </ul>
*
* <p>A thread in the waiting state is waiting for another thread to
* perform a particular action.
*
* For example, a thread that has called <tt>Object.wait()</tt>
* on an object is waiting for another thread to call
* <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
* that object. A thread that has called <tt>Thread.join()</tt>
* is waiting for a specified thread to terminate.
*/
//等待(没有时间的限制的等待)
WAITING,
/**
* Thread state for a waiting thread with a specified waiting time.
* A thread is in the timed waiting state due to calling one of
* the following methods with a specified positive waiting time:
* <ul>
* <li>{@link #sleep Thread.sleep}</li>
* <li>{@link Object#wait(long) Object.wait} with timeout</li>
* <li>{@link #join(long) Thread.join} with timeout</li>
* <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
* <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
* </ul>
*/
//超时等待(会有时间的限制)
TIMED_WAITING,
/**
* Thread state for a terminated thread.
* The thread has completed execution.
*/
//终止
TERMINATED;
}
wait/sleep 区别
4.1来自不同的类
wait =>Object
sleep => Thread
企业中的休眠会用sleep的吗?不会,一般使用`
import java.util.concurrent.TimeUnit;
TimeUnit.DAYS.sleep(1);
4.2.关于锁的释放
wait :会释放锁 (不需要捕获异常)
等待的条件必须在同步代码块中。
sleep: 睡觉了,抱着睡觉,不会释放!(需要捕获异常)
5.Lock锁的详细讲解(important)
synchronized和Lock锁的区别
- sychronized是内置java关键字,Lock是一个java类(接口)
- sychronized适合锁少量的代码,Lock适合大量的代码
- sychronized 无法判断锁的状态,Lock可以获取锁的状态。
- sychronized 会自动释放锁,Lock需要手动关闭锁!,如果不释放会产生死锁。
- 线程1(获取锁,阻塞)线程2(等待、傻傻的等待),Lock锁就不一定等待下去。
- sychronized 可重入锁,不可以中断的,非公平 Lock,可以重入锁,可以判断锁,公平或者不公平可以手动的设置。
5.1sychronized实现并发处理:
package com.hou.demo;
/*
* 真正的多线程开发,
* 企业开发,线程是一个单独的资源类,没有任何的附属操作
* 1. 属性方法
* */
public class SaleTicketDemo01 {
public static void main(String[] args) {
// new Thread(new MyThread()).start();
// 并发:多线程操作同一个资源类,把资源类丢入线程
// @FunctionalInterface 函数式接口,jdk1.8 lamda表达式
final Ticket ticket=new Ticket();
//这个是通过匿名函数进行实现的
/* new Thread(new Runnable() {
@Override
public void run() {
}
}).start();*/
//lamda表达式的()为传入的参数的名称,{}写入你的代码,后面的”A"为你的线程的名字
new Thread(()->{
for (int i = 0; i < 60; i++) {
ticket.sale();
}
},"A").start();
new Thread(()->{
for (int i = 0; i < 60; i++) {
ticket.sale();
}
},"B").start();
new Thread(()->{
for (int i = 0; i < 60; i++) {
ticket.sale();
}
},"C").start();
}
/* 企业不会用这个开发性能低
static class MyThread implements Runnable{
@Override
public void run() {
}
}*/
// 资源类oop
static class Ticket{
private Integer num=20;
// 卖票的方式 传统的synchronized可以解决这个高并发的问题
public synchronized void sale(){
if(num>0) {
System.out.println(Thread.currentThread().getName()+"卖出了"+(num-num)+"票,剩余:"+(num--));
}
}
}
}
5.111 sychronized优化
可以把锁的粒度变细,只锁住需要锁住的地方。
变粗,很多地方锁住了,有时可以合并为锁住一个地方。
锁住在对象的时候加上 final关键字
不要使用下面方式锁:
String s1 = "hello";
void m(){
sychronized(s1){
}
5.2 Lock锁实现并发处理:
1. new RreentrantLock
2. try{lock.lock(); //锁定的方法}catch{}
3.进行锁的释放(lock.unlock())
4. 代码实现如下所示:
package com.hou.demo;
/*
* 真正的多线程开发,
* 企业开发,线程是一个单独的资源类,没有任何的附属操作
* 1. 属性方法
* */
public class SaleTicketDemo01 {
public static void main(String[] args) {
// new Thread(new MyThread()).start();
// 并发:多线程操作同一个资源类,把资源类丢入线程
// @FunctionalInterface 函数式接口,jdk1.8 lamda表达式
final Ticket ticket=new Ticket();
//这个是通过匿名函数进行实现的
/* new Thread(new Runnable() {
@Override
public void run() {
}
}).start();*/
//lamda表达式的()为传入的参数的名称,{}写入你的代码,后面的”A"为你的线程的名字
new Thread(()->{
for (int i = 0; i < 60; i++) {
ticket.sale();
}
},"A").start();
new Thread(()->{
for (int i = 0; i < 60; i++) {
ticket.sale();
}
},"B").start();
new Thread(()->{
for (int i = 0; i < 60; i++) {
ticket.sale();
}
},"C").start();
}
/* 企业不会用这个开发性能低
static class MyThread implements Runnable{
@Override
public void run() {
}
}*/
// 资源类oop
static class Ticket{
private Integer num=20;
// 卖票的方式 传统的synchronized可以解决这个高并发的问题
public synchronized void sale(){
if(num>0) {
System.out.println(Thread.currentThread().getName()+"卖出了"+(num-num)+"票,剩余:"+(num--));
}
}
}
}
6.生产者消费者sychronized版本
生产者消费者sychronized版本
6.1代码实现如下:
package pc;
// 线程交替执行 A B 操作同一个变量
public class ATest {
public static void main(String[] args) {
Data data = new Data();
new Thread(()->{
try {
for (int i = 0; i < 5; i++) {
data.increment();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"A").start();
new Thread(()->{
try {
for (int i = 0; i < 5; i++) {
data.decrement();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"B").start();
new Thread(()->{
try {
for (int i = 0; i < 5; i++) {
data.increment();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"C").start();
new Thread(()->{
try {
for (int i = 0; i < 5; i++) {
data.decrement();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"D").start();
}
// 判断等待,业务, 通知
static class Data{ //数字 资源类
private int number = 0;
// +1
public synchronized void increment() throws InterruptedException {
// 需要把if变为while 防止虚假唤醒
while (number!=0) {
// 等待
this.wait();
}
number++;
System.out.println(Thread.currentThread().getName() + "=>" + number);
// 通知线程其他线程,我+1完毕了
this.notifyAll();
}
// -1
public synchronized void decrement() throws InterruptedException {
while(number==0){
//等待
this.wait();
}
number--;
System.out.println(Thread.currentThread().getName() + "=>" + number);
// 通知其他的线程,我-1完毕了
this.notifyAll();
}
}
}
7.生产者消费者Lock版本
lock版本
7.1代码实现如下:
package com.hou.demo;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/*
* 真正的多线程开发,
* 企业开发,线程是一个单独的资源类,没有任何的附属操作
* 1. 属性方法
* */
public class SaleTicketDemo02 {
public static void main(String[] args) {
Ticket ticket=new Ticket();
//lamda表达式的()为传入的参数的名称,{}写入你的代码,后面的”A"为你的线程的名字
new Thread(()->{ for (int i = 0; i < 60; i++) ticket.sale(); },"A").start();
new Thread(()->{
for (int i = 0; i < 60; i++)
ticket.sale();
},"B").start();
new Thread(()->{ for (int i = 0; i < 60; i++)
ticket.sale(); },"C").start();
}
// Lock
static class Ticket{
private Integer num=20;
int i=0;
Lock lock=new ReentrantLock(); //它的实现类有ReentrantLock,ReadLock
public void sale(){
lock.lock();
try {
if(num>0) {
System.out.println(Thread.currentThread().getName()+"卖出了"+(i++)+"票,剩余:"+(num--));
}
}catch (Exception e){
lock.unlock();//解锁
e.printStackTrace();
}
}
}
}
8.防止虚假唤醒把其中的if变为while实现
9.Condition可以做到精准通知和唤醒线程 也就是可以让线程有序的执行
9.1代码如下:
package pc;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ConditionTest {
public static void main(String[] args) {
Data3 data3 = new Data3();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data3.print1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"A").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data3.print2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"B").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data3.print3();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"C").start();
}
// 使用Condition实现精准通知
static class Data3{
private int num=1; //num为1让A执行 2让B执行 3C
Lock lock=new ReentrantLock();
private Condition condition1= lock.newCondition();
private Condition condition2 = lock.newCondition();
private Condition condition3 = lock.newCondition();
public void print1() throws InterruptedException {
try {
lock.lock();
while (num!=1){
// 等待
condition1.await();
}
num=2;
System.out.println(Thread.currentThread().getName() + "=>AAAAAAAA");
//唤醒B
condition2.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void print2() throws InterruptedException {
try {
lock.lock();
while (num!=2){
// 等待
condition2.await();
}
num=3;
System.out.println(Thread.currentThread().getName() + "=>BBBBBBBB");
//唤醒B
condition3.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void print3() throws InterruptedException{
try {
lock.lock();
while (num!=3){
condition3.await();
}
num=1;
System.out.println(Thread.currentThread().getName() + "=>CCCCCCCCCCCCC");
condition1.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
10.集合的线程安全类CopyOnWriteArrayList,底层通过Lock接口实现线程的安全
- ArrayList通过多线程进行访问的时候会报出异常
- Vector是集合类中线程安全的,通过传统的 synchronized方法进行的实现
- Collections.synchronizedList(new ArrayList<>());这个方法底层同样是使用synchronized方法实现的线程安全,不推荐使用。
- CopyOnWriteArrayLIst,通过Lock接口,lock,unlock方法实现的线程安全,性能相比synchronized的要好,推荐用这个实现线程安全。
代码如下:
package unsafe;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
public class ListTest {
public static void main(String[] args) {
// 1. List<String> list = Arrays.asList(); //不是线程安全的,会抛出相关的异常
// Exception in thread "2" java.lang.UnsupportedOperationException
// List<Object> list = new CopyOnWriteArrayList<>(); // 使用Lock接口进行实现的方法
// List<String> list = Collections.synchronizedList(new ArrayList<>()); //使用的是传统的sychronized方法
List<String> list = new Vector<>(); //使用的是synchronized关键字实现的线程安全
for (int i = 0; i < 8; i++) {
new Thread(()->{
list.add(UUID.randomUUID().toString().substring(0,6));
System.out.println(list);
},String.valueOf(i)).start();
}
}
}
10.集合的线程安全类CopyWriteOnArraySet
11.Callable实现多线程
- 有返回值
- 可以抛出异常
- 使用call()方法
- 有缓存,可能会阻塞
5.代码实现如下:
package com.hou.demo.callabe;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class CallabeTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
Mythread mythread=new Mythread();
FutureTask futureTask = new FutureTask(mythread);
new Thread(futureTask,"A").start();
new Thread(futureTask,"B").start(); //第二个线程的执行结果会进行缓存,效率高
String o = (String) futureTask.get(); //获取RunnableR 返回结果,这个方法可能会产生阻塞,所以放到最后
System.out.println(o);
}
}
class Mythread implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println("call()------");
return "goodJob";
}
}
12.并发实现的常用辅助类
12.1 CountDownLatch
每次有计数器执行countDown()数量-1,假设计数器变为0,countDownLatch.await()就会被唤醒,继续执行。
代码如下:
package com.hou.demo.add;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierDemo {
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();//等待
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
},String.valueOf(i)).start();
}
}
}
12.2CycliBarrier
package com.hou.demo.add;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierDemo {
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();//等待
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
},String.valueOf(i)).start();
}
}
}
代码如下:
12.3 Semaphore
代码如下:
new Semaphore(3)
可以限制线程的数量
semaphore.acquire()获得车位,也就是线程的数量,可以限制线程的数量!!!,也就是可以用来限流
semaphore.release()释放停车位,然后等待被抢占。
package com.hou.demo.add;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class SemaphoreDemo {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(3);
for (int i = 1; i <=6 ; i++) {
new Thread(()->{
try {
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();
}
}
}
13.ReadWriteLock的实现
**独占锁(写锁):**只允许一个线程进行写入
**共享锁(读锁):**允许多个线程进行写入。
代码实现如下:
package com.hou.demo.add;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class ReadWriteLockDemo {
public static void main(String[] args) {
MyLock myLock = new MyLock();
for (int i = 1; i <= 9; i++) {
final int temp=i;
new Thread(()->{
myLock.put(temp+"",temp+"");
},String.valueOf(i)).start();
}
//读入的测试
for (int i = 1; i <= 6; i++) {
final int temp=i;
new Thread(()->{
myLock.read(temp+"");
},String.valueOf(i)).start();
}
}
}
class MyLock{
// 读写锁更加细粒度的控制
private ReadWriteLock readWriteLock=new ReentrantReadWriteLock();
private volatile Map<String,String> map=new HashMap<>();
// 存,放,只希望只有一个线程写入
public void put(String key,String value){
readWriteLock.writeLock().lock();
try {
// readWriteLock.readLock().lock(); 注意这里是writeLock()
System.out.println(Thread.currentThread().getName()+"进行写入"+key);
map.put(key,value);
System.out.println(Thread.currentThread().getName()+"写入ok");
}catch (Exception e){
e.printStackTrace();
}finally {
readWriteLock.writeLock().unlock();
}
}
// 读 所有的人可以读
public void read(String key){
try {
readWriteLock.readLock().lock();
System.out.println(Thread.currentThread().getName() + "读入" + key);
String s = map.get(key);
System.out.println(Thread.currentThread().getName() + "读入ok");
} catch (Exception e) {
e.printStackTrace();
} finally {
// 读锁进行释放
readWriteLock.readLock().unlock();
}
}
}
volatile关键字具有并发三大特性的两大
可见性
对于所有的线程可见的
有序性
在它的变量之前的代码,不可以变更到它的后面,同理,后面
原子性
不可以保证原子性
14.BlockingQueue阻塞队列实现线程的几种方式
使用情况: 多线程时使用,阻塞队列,线程池
学会使用:添加,移除。
它有四组API:
- 抛出异常
- 不会抛出异常
- 阻塞等待
- 超时等待
方式 | 方法 | 有返回值,不抛出异常 | 阻塞一直等待 | 超时等待 |
---|---|---|---|---|
添加 | add | offer()返回true,false | put() | offer(,,) |
移除 | remove | poll() | take() | poll(,) |
判断队列首 | element | peek | - | - |
代码实现如下:
package com.hou.demo.bq;
import java.util.Collection;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
public class TestBlockingQueue {
public static void main(String[] args) throws InterruptedException {
// test();
// test2();
test3();
}
/*
* 抛出异常
*
* */
public static void test(){
ArrayBlockingQueue<Object> arrayBlockingQueue = new ArrayBlockingQueue<>(3);
arrayBlockingQueue.add("1");
arrayBlockingQueue.add("2");
arrayBlockingQueue.add("3");
System.out.println(arrayBlockingQueue);
// Queue full
// arrayBlockingQueue.add("4");
arrayBlockingQueue.remove();
arrayBlockingQueue.remove();
arrayBlockingQueue.remove();
// java.util.NoSuchElementException
// 一次只移除一个元素
arrayBlockingQueue.remove();
}
public static void test1(){
ArrayBlockingQueue<Object> arrayBlockingQueue = new ArrayBlockingQueue<>(3);
arrayBlockingQueue.offer("1");
arrayBlockingQueue.offer("2");
// 返回true
System.out.println(arrayBlockingQueue.offer("3"));
System.out.println(arrayBlockingQueue);
System.out.println("element方法输出:"+arrayBlockingQueue.element());
System.out.println("peek方法输出:" + arrayBlockingQueue.peek());
}
/*
*
* 等待一直阻塞
* */
public static void test2() throws InterruptedException {
ArrayBlockingQueue<Object> arrayBlockingQueue = new ArrayBlockingQueue<>(3);
arrayBlockingQueue.put("1");
arrayBlockingQueue.put("2");
arrayBlockingQueue.put("3");
// arrayBlockingQueue.put("4"); //插入队列不进,等待一直阻塞,不会抛出异常
System.out.println(arrayBlockingQueue.take());
System.out.println(arrayBlockingQueue.take());
System.out.println(arrayBlockingQueue.take());
// 等待阻塞也不会抛出异常
System.out.println(arrayBlockingQueue.take());
}
/*
* 等待超时等待
*
* */
public static void test3() throws InterruptedException {
ArrayBlockingQueue<Object> arrayBlockingQueue = new ArrayBlockingQueue<>(3);
arrayBlockingQueue.offer("11");
arrayBlockingQueue.offer("22");
arrayBlockingQueue.offer("33");
arrayBlockingQueue.offer("44",3, TimeUnit.SECONDS);
// poll方法
arrayBlockingQueue.poll();
System.out.println(arrayBlockingQueue.poll());
System.out.println(arrayBlockingQueue.poll());
arrayBlockingQueue.poll(2,TimeUnit.SECONDS);
}
}
四组API
- 抛出异常
- 不抛出异常
- 阻塞等待
- 超时等待
同步队列(SynchronousQueue)
线程进行put进去的时候,需要take出来才可以再次put.
相关的code:
package com.hou.demo.bq;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
public class TestSynchronousQueue {
public static void main(String[] args) {
BlockingQueue<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(2);
System.out.println(Thread.currentThread().getName()+"得到"+synchronousQueue.take());
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName()+"得到"+synchronousQueue.take());
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName()+"得到"+synchronousQueue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
},"T2").start();
}
}
15池化技术和线程池的使用
程序:占用cpu的资源
线程池,连接池,内存池。
线程池:提前提供一些资源,有人要用就来这里拿,用完返回给我就好!
线程池不允许使用Executors云创建,而是通过ThreadPoolExecutor的方式,可以更加明确线程池的运行规则。规避资源耗尽的风险。
[外链图片转存中…(img-Ar5UBjLm-1640677108884)]
15.1OOM:OutofMemory
线程三大方法,7大参数,4种拒绝策略。
线程池的好处:
管理线程
提高响应的速度
方便管理
线程复用、可以控制最大并发数,管理线程。
三大方法实现如下:
package com.hou.demo.pool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestExecutors {
public static void main(String[] args) {
ExecutorService executorService = Executors.newSingleThreadExecutor(); //创建单个线程池
ExecutorService executorService1 = Executors.newFixedThreadPool(6);//创建固定个数的线程
ExecutorService executorService2 = Executors.newCachedThreadPool();//创建不确定的线程池的个数,遇强则强,遇弱则弱,根据你的CPU性能来的。
try {
for (int i = 0; i < 10; i++) {
// 使用了线程池以后,使用线程池来创建线程
executorService1.execute(()->{
System.out.println(Thread.currentThread().getName() + "执行了");
});
}}
catch (Exception e) {
e.printStackTrace();
} finally {
// 注意一定要关闭线程池
executorService1.shutdown();
}
}
}
三个方法相关的源码:
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
public ThreadPoolExecutor(int corePoolSize, //核心线程大小
int maximumPoolSize, //线程最大线程数
long keepAliveTime, //超时了没有人调用会释放
TimeUnit unit, //超时单位
BlockingQueue<Runnable> workQueue) {//阻塞队列
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
拒绝策略,阻塞队列:
[外链图片转存中…(img-tii9qnJS-1640677108903)]
7大参数:
注意线程池的创建需要用这个new ThreadPoolExecutor()方法,不可以用上面的三种,因为会造成资源的浪费。它里面默认的线程数是 Integer.MAX_VALUE约为21亿,阿里巴巴开发手册里面有这样写。
// 不建议使用上面三种进行创建线程 上面为源码的相关的参数
ExecutorService threadPoolExecutor = new ThreadPoolExecutor(2
,5,
// 这个为超时不会等待的时间
3,
TimeUnit.SECONDS,new LinkedBlockingQueue<>(3),//这个为允许阻塞的线程数量
Executors.defaultThreadFactory(),//这个参数基本不会改变
new ThreadPoolExecutor.AbortPolicy()//有四大拒绝策略,银行满了,还有人进行,不处理这个人,抛出异常。
);
四大拒绝策略:
- new ThreadPoolExecutor.CallerRunsPolicy()
- new ThreadPoolExecutor.AbortPolicy()
- new ThreadPoolExecutor.DiscardPolicy()
- new ThreadPoolExecutor.DiscardOldestPolicy()
代码实现:
// 不建议使用上面三种进行创建线程 上面为源码的相关的参数
ExecutorService threadPoolExecutor = new ThreadPoolExecutor(2
,5,
// 这个为超时不会等待的时间
3,
TimeUnit.SECONDS,new LinkedBlockingQueue<>(3),//这个阻塞的线程数量3个
Executors.defaultThreadFactory(),
// 1. new ThreadPoolExecutor.AbortPolicy()银行满了,还有人进行,不处理这个人,抛出异常。
// 2. new ThreadPoolExecutor.CallerRunsPolicy 哪里来的去哪里
// 使用这个拒绝策略的条件:线程数一定要超过最大线程数才会进行触发 比如:这里8<9线程至少从9开始 执行结果
// new ThreadPoolExecutor.CallerRunsPolicy()
/* pool-4-thread-1ok
pool-4-thread-2ok
pool-4-thread-2ok
pool-4-thread-2ok
pool-4-thread-3ok
mainok
pool-4-thread-1ok
pool-4-thread-4ok
pool-4-thread-5ok*/
// 3. new ThreadPoolExecutor.DiscardPolicy() //队列满了,会丢掉任务,不会抛出异常
/* pool-4-thread-1ok
pool-4-thread-5ok
pool-4-thread-4ok
pool-4-thread-4ok
pool-4-thread-2ok
pool-4-thread-3ok
pool-4-thread-5ok
pool-4-thread-1ok */
//4
new ThreadPoolExecutor.DiscardOldestPolicy() // 队列满了,会尝试去竞争,不会抛出异常。
);
工作中使用这个进行创建线程池
ExecutorService threadPoolExecutor = new ThreadPoolExecutor(2
,5,
// 这个为超时不会等待的时间
3,
TimeUnit.SECONDS,new LinkedBlockingQueue<>(3),//这个为允许阻塞的线程数量
Executors.defaultThreadFactory(),//这个参数基本不会改变
new ThreadPoolExecutor.AbortPolicy()//有四大拒绝策略,银行满了,还有人进行,不处理这个人,抛出异常。
);
全部实现代码:
package com.hou.demo.pool;
import java.util.concurrent.*;
public class TestExecutors {
public static void main(String[] args) {
// 工具类三大方法,但是我们不要使用这种方式进行创建,需要使用底层的ThreadPoolExecutor进行这个的创建,避免会浪费资源。
ExecutorService executorService = Executors.newSingleThreadExecutor(); //创建单个线程池
ExecutorService executorService1 = Executors.newFixedThreadPool(6);//创建固定个数的线程
ExecutorService executorService2 = Executors.newCachedThreadPool();//创建不确定的线程池的个数,遇强则强,遇弱则弱,根据你的CPU性能来的。
// 不建议使用上面三种进行创建线程 上面为源码的相关的参数
ExecutorService threadPoolExecutor = new ThreadPoolExecutor(2
,5,
// 这个为超时不会等待的时间
3,
TimeUnit.SECONDS,new LinkedBlockingQueue<>(3),//这个阻塞的线程数量3个
Executors.defaultThreadFactory(),
// 1. new ThreadPoolExecutor.AbortPolicy()银行满了,还有人进行,不处理这个人,抛出异常。
// 2. new ThreadPoolExecutor.CallerRunsPolicy 哪里来的去哪里
// 使用这个拒绝策略的条件:线程数一定要超过最大线程数才会进行触发 比如:这里8<9线程至少从9开始 执行结果
// new ThreadPoolExecutor.CallerRunsPolicy()
/* pool-4-thread-1ok
pool-4-thread-2ok
pool-4-thread-2ok
pool-4-thread-2ok
pool-4-thread-3ok
mainok
pool-4-thread-1ok
pool-4-thread-4ok
pool-4-thread-5ok*/
// 3. new ThreadPoolExecutor.DiscardPolicy() //队列满了,会丢掉任务,不会抛出异常
/* pool-4-thread-1ok
pool-4-thread-5ok
pool-4-thread-4ok
pool-4-thread-4ok
pool-4-thread-2ok
pool-4-thread-3ok
pool-4-thread-5ok
pool-4-thread-1ok */
//4
new ThreadPoolExecutor.DiscardOldestPolicy() // 队列满了,会尝试去竞争,不会抛出异常。
);
try {
// 注意一下这里是线程池进行创建线程,不用new Thread().start();而是使用threadPoolExecutor.execute(()->{})这个方法进行创建
for (int i = 1; i <=100; i++) {
// 使用了线程池以后,使用线程池来创建线程
/* executorService1.execute(()->{
System.out.println(Thread.currentThread().getName() + "执行了");
});*/
threadPoolExecutor.execute(()->{
System.out.println(Thread.currentThread().getName() + "ok");
});
}}
catch (Exception e) {
e.printStackTrace();
} finally {
// 注意一定要关闭线程池
threadPoolExecutor.shutdown();
}
}
}
可以知道这里的最大线程个数为:,new LinkedBlockingQueue<>(capacity:3)+maximumPoolSize(5)=8个,如果超出指定的线程则会抛出下面这个异常。
异常:
pool-4-thread-1ok
pool-4-thread-3ok
pool-4-thread-2ok
pool-4-thread-3ok
pool-4-thread-1ok
pool-4-thread-4ok
pool-4-thread-5ok
pool-4-thread-2ok
java.util.concurrent.RejectedExecutionException: Task com.hou.demo.pool.TestExecutors$$Lambda$1/1831932724@7699a589 rejected from java.util.concurrent.ThreadPoolExecutor@58372a00[Running, pool size = 5, active threads = 1, queued tasks = 0, completed tasks = 7]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:823)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1369)
at com.hou.demo.pool.TestExecutors.main(TestExecutors.java:33)
细节:
1.当线程数目小于maximumPoolSize,只会通过corePoolSize,也就是核心 线程进行执行,等到超过了最大线程数目的时候才会通过最大的线程数目进行执行。
2.new ThreadPoolExecutor.CallerRunsPolicy(),这个线程是通过main线程进行拒绝的。
3.线程池一定要关闭,通过这个方法进行关闭,可以在 finally语句里面进行关闭 threadPoolExecutor.shutdown();
线程池的最大数量怎么设置:
判断是:IO密集型还是CPU密集型,可以手动的获取CPU的处理器的数量
package com.hou.demo.pool;
import java.util.concurrent.*;
public class TestExecutors1 {
public static void main(String[] args) {
int i1 = Runtime.getRuntime().availableProcessors();//获取CPU的处理器的个数
// CPU密集型 几核就是几,可以充分利用CPU。
// IO密集型 可以进行判断消耗io的线程
//程序 15在大型任务 io十分占用资源
// IO密集型
System.out.println(i1);
ExecutorService threadPoolExecutor = new ThreadPoolExecutor(2, i1, 2,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(3),
Executors.defaultThreadFactory(),
// 这个是通过main线程进行拒绝的
new ThreadPoolExecutor.CallerRunsPolicy());
try {
// 注意一下这里是线程池进行创建线程,不用new Thread().start();而是使用threadPoolExecutor.execute(()->{})这个方法进行创建
for (int i = 1; i <=20; i++) {
threadPoolExecutor.execute(()->{
System.out.println(Thread.currentThread().getName() + "ok");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
threadPoolExecutor.shutdown();
}
}
}
16 CAS(Compare and Set)
一种无锁,自旋,乐观锁思想。
底层是 CPU原语操作不会被中断
CAS(V,Expected,NewValue);
if(V == E)
V = NewValue
otherswise try again or fail
这段代码是cpu原语支持,不会中途中断。
16.1 出现ABA问题和解决办法
有时候被期望的值被其他 线程修改,又被其他线程修改回来了,但是你不知道
解决:1.可以加一个版本号进行记录一下修改的次数,version,修改一次加1,这样可以找到
2. 可以通过提供的 AtomicStampedRefrence这个类是集成了version的,可以 solve it.
一般基础类型没有什么问题,如果是 引用类型就会出现一些问题
底层的unsafe类可以直接操作java JVM的里面的内存