JUC并发——多线程锁

 锁:

分类:
1、公平锁:十分公平:可以先来后到;效率相对低
2、非公平锁:十分不公平:可以插队 (默认)**  线程饿死,效率高
3、可重入锁:synchronize(隐式)和lock(显式)
(1)可重入锁:synchronize(隐式)

package com.xsb.sync;

import java.util.concurrent.locks.ReentrantLock;

//synchronized可重入锁
public class SynclockDemo {
    public static void main(String[] args) {
        Object o = new Object();
        new Thread(()->{
            synchronized (o){
                System.out.println(Thread.currentThread().getName()+"外层");

                synchronized (o) {
                    System.out.println(Thread.currentThread().getName() + "中层");

                    synchronized (o) {
                        System.out.println(Thread.currentThread().getName() + "内层");

                    }
                }
                    }
        },"aa").start();

    }
}

2、lock锁

package com.xsb.lock;

import java.util.concurrent.locks.ReentrantLock;

//lock可重入锁,手动释放锁
public class LockDemo {
    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();//ReentrantLock默认使用非公平锁,public ReentrantLock() {sync = new ReentrantLock.NonfairSync();
            //创建线程
        new Thread(()->{
            try {
                //上锁
                lock.lock();
                System.out.println(Thread.currentThread().getName()+"外层");
            }finally {
                //解锁
                lock.unlock();
            }
            try {
                //上锁
                lock.lock();
                System.out.println(Thread.currentThread().getName()+"内层");
            }finally {
                //解锁
                lock.unlock();
            }
        },"t1").start();

    }
}

4、死锁

 两个或者两个以上进程在执行过程中,因为争夺资源而造成一种相互等待的现象,如果没有外力干涉,他们无法在执行下去。

package com.xsb.sisuo;

import java.util.concurrent.TimeUnit;

//死锁演示
public class DeadLock {
    static Object a = new Object();
    static Object b = new Object();
    public static void main(String[] args) {
        new Thread(()->{
            synchronized (a){
                System.out.println(Thread.currentThread().getName() +"持有锁a,试图获取锁b");
            }
            synchronized (b) {
                System.out.println(Thread.currentThread().getName() + "获取锁b");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"aa").start();

        new Thread(()->{
            synchronized (b){
                System.out.println(Thread.currentThread().getName() +"持有锁b,试图获取锁a");
                try {
                    TimeUnit.SECONDS.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            synchronized (a) {
                System.out.println(Thread.currentThread().getName() + "获取锁a");
            }
        },"bb").start();
    }
}

产生死锁原因:系统资源不足;进程运行推进顺序不合适;资源分配不当

验证是否是死锁:(1):jps -l  (2):jstack jvm自带堆栈跟踪工具 jstack 端口号

5、阻塞队列

是一个队列,通过共享的队列,可以使数据由队列的一端输入,从另一端输出。

 6、常见的阻塞队列(BlockingQueue)

(1)、ArrayBlockingQueue:基于数组的阻塞队列

package com.xsb.queue;
//ArrayBlockingQueue阻塞队列,add()方法
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class BlockingQueueDemo {
    public static void main(String[] args) {
        BlockingQueue<String > queue = new ArrayBlockingQueue<>(3);
        System.out.println(queue.add("a"));
        System.out.println(queue.add("b"));
        System.out.println(queue.add("c"));
        //System.out.println(queue.add("c"));//队列满,抛出异常
        //System.out.println(queue.element());//检查元素
        System.out.println(queue.remove());
        System.out.println(queue.remove());//取元素
    }
}

 7、线程池(Thread Pool):一种线程使用模式

(1)池化技术

程序的运行,本质:占用系统的资源! 

优化资源的使用!=>池化技术

池化技术:事先准备好一些资源,有人要用,就来我这里拿,用完之后还给我。
(2)、线程池的好处

降低资源的消耗;

提高响应的速度;

重复利用;

方便管理。

即:线程复用、可以控制最大并发数、管理线程

(3)、线程池使用方式

a、Executors.newFixedThreadPoll(int):一池N线程

b、Executors.newSingleThreadExecutor():一个任务一个的执行,一池一线程

c、Executors.nweCachedThreadPoll():线程池根据需求创建线程,可扩容

package com.xsb.pool;

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

public class ThreadPoolDemo {
    public static void main(String[] args) {
        //一池五线程
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        //一池一线程
        ExecutorService threadPool1 = Executors.newSingleThreadExecutor();//一个窗口
        //一池可扩容
        ExecutorService threadPool2 = Executors.newCachedThreadPool();
        try {
            for (int i = 1; i <=10 ; i++) {
                threadPool2.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"办理业务");
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
                //关闭
            threadPool2.shutdown();
        }
    }
}

(4)、线程池7个参数

(5)、工作流程

 

 (6)、自定义线程池

为什么不使用:Executors

 自定义:

package com.xsb.pool;

import java.util.concurrent.*;

//自定义线程池
public class ThreadPool {
    public static void main(String[] args) {
        ExecutorService threadPool= new ThreadPoolExecutor(
                2,//常驻线程
                5,//最大线程
                2L,//存活时间
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(3),//阻塞队列大小
                Executors.defaultThreadFactory(), //线程工厂
                new ThreadPoolExecutor.AbortPolicy()
        );
        try {
            for (int i = 1; i <=10 ; i++) {
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"办理业务");
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭
            threadPool.shutdown();
        }
    }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值