Java并发面试算法题目

实现一个生产者,消费者

思路:用lock锁。定义一个类成员变量 max_value,min_value代表资源的最大,最小数量。

java 复制代码
package org.app.common;

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

public class Resource {
        private int MAX_VALUE= 3;  
        private  int MIN_VALUE=0;
        private   int number = 0;
        private Lock lock = new ReentrantLock();
        private Condition condition = lock.newCondition();
        public void consume(){
            try {
                lock.lock();
                while(number <= MIN_VALUE){
                    condition.await();
                }
                number--;
                System.out.println("【消费者】:消费了一个产品,【现仓储量为】:" + number);
                condition.signalAll();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
        public void produce(){
            try {
                lock.lock();
                while (number >MAX_VALUE) {
                    condition.await();
                }
                number++;
                System.out.println("【生产者】:生产了一个产品\t【现仓储量为】:" + number);
                condition.signalAll();
            }catch (Exception e){

            }finally {
                lock.unlock();
            }
        }
    public static void main(String[] args) {
        Resource resouce = new Resource();
        new Thread(()->{
            for(int i=0;i<10;i++){
                resouce.produce();
            }
        }).start();//生产者
        //消费者
        new Thread(()->{
            for (int i=1;i<=5;i++){
                resouce.consume();
            }
        },String.valueOf("消费者")).start();
    }
}

线程交替打印问题

2个线程交替打印1-10

问题解决方法比较多。

java 复制代码
private static volatile int num = 1;
private static Object lock = new Object();
    public static void main(String[] args) {
        Thread t1 = new Thread() {
            public void run() {
                while (num < 99) {
                    if (num % 2 == 0) {
                        synchronized (lock) {
                            lock.notify();
                            System.out.println("t1" + "_" + num);
                            num++;
                            try {
                                lock.wait();
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                }
            }
        };
        Thread t2 = new Thread() {
            public void run() {
                while (num < 99) {
                    if (num % 2 == 1) {
                        synchronized (lock) {
                            lock.notify();
                            System.out.println("t2" + "_" + num);
                            num++;
                            try {
                                lock.wait();
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                }
            }
        };
        t1.start();
        t2.start();
java 复制代码
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Main2 {
    private int time;
    private int state;
    private Lock lock = new ReentrantLock();
    public Main2(int time){
        this.time = time;
    }
    public void print(String name,int targetNum){
        for(int i=0;i<time;){
            lock.lock();
            if (state % 3 == targetNum) {
                state++;
                i++;
                System.out.println(name);
            }
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        Main2 main2 = new Main2(2);
        new Thread(()->{
            main2.print("B", 1);
        },"B").start();      new Thread(()->{
            main2.print("C", 2);
        },"C").start();
        new Thread(()->{
            main2.print("A", 0);
        },"A").start();
    }
}
相关推荐
Mahir081 天前
Spring 循环依赖深度解密:从问题本质到三级缓存源码级解析
java·后端·spring·缓存·面试·循环依赖·三级缓存
RyFit1 天前
SpringAI 常见问题及解决方案大全
java·ai
石山代码1 天前
C++ 内存分区 堆区
java·开发语言·c++
心中有国也有家1 天前
cann-recipes-infer:昇腾 NPU 推理的“菜谱集合”
经验分享·笔记·学习·算法
绝知此事1 天前
【算法突围 01】线性结构与哈希表:后端开发的收纳术
java·数据结构·算法·面试·jdk·散列表
无风听海1 天前
C# 隐式转换深度解析
java·开发语言·c#
碧海银沙音频科技研究院1 天前
通话AEC与语音识别AEC的软硬回采链路
深度学习·算法·语音识别
一只大袋鼠1 天前
Git 进阶(二):分支管理、暂存栈、远程仓库与多人协作
java·开发语言·git
csdn_aspnet1 天前
Python 算法快闪 LeetCode 编号 70 - 爬楼梯
python·算法·leetcode·职场和发展