# Java--多线程--JUC、死锁、lock、生产者与消费者问题、线程池

Java–多线程–JUC、死锁、lock、生产者与消费者问题、线程池

JUC

package com.zy.thread;

import java.util.concurrent.CopyOnWriteArrayList;

/**
 *description: Java--多线程--JUC
 *@program: 基础语法
 *@author: zy
 *@create: 2023-03-28 21:13
 */
public class StudyThreadJUC {

    public static void main(String[] args) {
        // 默认线程安全
        CopyOnWriteArrayList list = new CopyOnWriteArrayList();
        for (int i = 0; i < 10000; i++) {
            new Thread(()->{
                list.add(Thread.currentThread().getName());
            }).start();
        }

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

        System.out.println("List大小:"+list.size());
    }
}

死锁

package com.zy.thread;

/**
 *description: Java--多线程--死锁
 *@program: 基础语法
 *@author: zy
 *@create: 2023-03-28 21:24
 */
public class StudyThreadDeadLock {

    /*
    死锁:多个线程互相抱着对方需要的资源,然后形成僵持。
    产生死锁的4个必要条件:
        1.互斥条件:一个资源每次只能被一个进程使用;
        2.请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放;
        3.不剥夺条件:进程已获得的资源,在未使用完之前,不能强行剥夺;
        4.循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系。
     */

    public static void main(String[] args) {
        Makeup g1 = new Makeup(0, "灰姑娘");
        Makeup g2 = new Makeup(1, "白雪公主");

        g1.start();
        g2.start();
    }
}

class Lipstick{

}

class Mirror{

}

class Makeup extends Thread{

    static Lipstick lipstick = new Lipstick();
    static Mirror mirror = new Mirror();

    int choice;
    String girlName;

    public Makeup(int choice,String girlName){
        this.choice = choice;
        this.girlName = girlName;
    }

    private void makeup() throws InterruptedException {
        if(choice == 0){
            synchronized (lipstick){
                // 获得口红锁
                System.out.println(this.girlName+"获得口红");
                Thread.sleep(1000);

                synchronized (mirror){
                    // 1秒钟后获得镜子
                    System.out.println(this.girlName+"获得镜子");
                }
            }
        }else{
            synchronized (mirror){
                // 获得口红锁
                System.out.println(this.girlName+"获得镜子");
                Thread.sleep(2000);

                synchronized (lipstick){
                    // 2秒钟后获得镜子
                    System.out.println(this.girlName+"获得口红");
                }
            }
        }
    }

    @Override
    public void run() {
        try {
            makeup();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

lock

package com.zy.thread.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 *description: Java--多线程--Lock
 *@program: 基础语法
 *@author: zy
 *@create: 2023-03-28 21:41
 */
public class StudyThreadLock {

    /*
    synchronized 与 Lock 的对比:
        1.lock锁是显示锁(手动开启和关闭),synchronized是隐式锁,出了作用域自动释放;
        2.lock只有代码块锁,synchronized有代码块锁和方法锁;
        3.使用lock锁,jvm将花费较少的时间来调度线程,性能更好。并且具有更好的扩展性(提供更多的子类);
        4.优先使用顺序:lock>同步代码块>同步方法。
     */

    public static void main(String[] args) {
        TestLock testLock = new TestLock();

        new Thread(testLock).start();
        new Thread(testLock).start();
        new Thread(testLock).start();
    }
}

class TestLock implements Runnable{

    int ticketNums = 10;

    // 定义可重入锁
    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true){
            // 加锁
            lock.lock();
            try {
                if(ticketNums>0){
                    Thread.sleep(1000);
                    System.out.println(ticketNums--);
                }else{
                    break;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                // 解锁
                lock.unlock();
            }
        }
    }
}

PCP–》管程法

package com.zy.thread.pcp;

/**
 *description: Java--多线程--生产者与消费者问题(多线程通信)
 * 利用缓冲区解决:管程法
 *@program: 基础语法
 *@author: zy
 *@create: 2023-03-28 22:07
 */
public class StudyThreadPCP {

    public static void main(String[] args) {
        Buffer buffer = new Buffer();

        new Productor(buffer).start();
        new Consumer(buffer).start();
    }
}

// 生产者
class Productor extends Thread{
    Buffer buffer;

    public Productor(Buffer buffer){
        this.buffer = buffer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            buffer.push(new Product(i));
            System.out.println("生产了"+i+"个产品");
        }
    }
}

// 消费者
class Consumer extends Thread{
    Buffer buffer;

    public Consumer(Buffer buffer){
        this.buffer = buffer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消费了-->"+buffer.pop().id+"个产品");
        }
    }
}

// 产品
class Product{
    int id;

    public Product(int id){
        this.id = id;
    }
}

// 缓冲区
class Buffer{

    // 产品容器
    Product[] products = new Product[10];
    // 产品计数
    int count;

    /**
     * @Description 生产
     * @author zy
     * [product]
     * void
     * @date 2023-3-28 22:17
     */
    public synchronized void push(Product product) {
        // 容器满了等待消费
        if(count == products.length){
            // 通知消费者消费,生产者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // 容器未满,丢入产品
        products[count] = product;
        count++;

        // 通知消费
        this.notify();
    }

    /**
     * @Description 消费
     * @author zy
     * []
     * com.zy.thread.pcp.Product
     * @date 2023-3-28 22:17
     */
    public synchronized Product pop() {
        // 判断消费
        if(count == 0){
            // 通知生产者生产,消费者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // 消费
        count--;
        Product product = products[count];
        // 通知生产
        this.notify();

        return product;
    }
}

PCP–》信号灯法

package com.zy.thread.pcp;

/**
 *description: Java--多线程--生产者与消费者问题(多线程通信)
 * 信号灯法:标志位解决
 *@program: 基础语法
 *@author: zy
 *@create: 2023-03-28 22:07
 */
public class StudyThreadPCP2 {

    public static void main(String[] args) {

        TV tv = new TV();

        new Player(tv).start();
        new Audience(tv).start();
    }
}

// 生产者--》演员
class Player extends Thread{

    private TV tv;

    public Player(TV tv){
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 1; i < 100; i++) {
            tv.play("第"+i+"个节目");
        }
    }
}

// 消费者--》观众
class Audience extends Thread{

    private TV tv;

    public Audience(TV tv){
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 1; i < 100; i++) {
            tv.watch();
        }
    }
}

// 产品--》节目
class TV{
    private String program;
    private boolean flag = true;

    public synchronized void play(String program){
        // 节目不存在,观众等待
        if(!flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("演员表演了:"+program);
        this.program = program;
        this.flag = !this.flag;
        this.notify();
    }

    public synchronized void watch(){
        // 节目存在,演员等待
        if(flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("观众观看了:"+program);
        this.flag = !this.flag;
        this.notify();
    }
}

线程池

package com.zy.thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import static java.lang.Thread.sleep;

/**
 *description: Java--多线程--线程池
 *@program: 基础语法
 *@author: zy
 *@create: 2023-03-28 23:06
 */
public class StudyThreadPool {


    public static void main(String[] args) {
        ExecutorService service = new ThreadPoolExecutor(3,10,3,
                TimeUnit.SECONDS,new ArrayBlockingQueue<>(4));

        /*ExecutorService service = Executors.newFixedThreadPool(10);*/

        //service.prestartAllCoreThreads();

        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());

        service.shutdown();
    }
}

class MyThread implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"--》"+i);
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值