写优先的读者写者问题(Java实现)

2024-03-10 21:10

本文主要是介绍写优先的读者写者问题(Java实现),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

该题系吉林大学19级软件学院操作系统课设题之一

 

 

先输入初始时的写者读者情况,优先级顺序做了随机处理

 

代码如下

GUI:


import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import java.util.concurrent.Semaphore;public class ReadAndWrite extends JFrame {public static Semaphore rw = new Semaphore(1);public static Semaphore mutex = new Semaphore(1);public static Semaphore w = new Semaphore(1);public static Semaphore fresh = new Semaphore(1);public static int count = 0;public static LinkedList<String> Re = new LinkedList<String>();//读空间public static LinkedList<String> Wr = new LinkedList<String>();//写空间public static LinkedList<String> ing = new LinkedList<String>();//正在的状态private int reader = 0;//写者数量和编号记录private int writer = 0;//读者数量和编号记录//三个大的文本区域static JTextPane jTextPane1 = new JTextPane();//读static JTextPane jTextPane2 = new JTextPane();//文件static JTextPane jTextPane3 = new JTextPane();//写ReadAndWrite(int a, int b){super("写优先的读者写者问题");reader = a+1;writer = b+1;for(int i = 1;i<=a;i++)new Thread(new Read(i)).start();for(int i = 1;i<=b;i++)new Thread(new Write(i)).start();setBounds(400,300,600,500);JPanel jPanel1 = new JPanel(new BorderLayout());//读JPanel jPanel2 = new JPanel(new BorderLayout());//临界区JPanel jPanel3 = new JPanel(new BorderLayout());//写jPanel1.setBackground(Color.CYAN);jPanel2.setBackground(Color.PINK);jPanel3.setBackground(Color.CYAN);this.add(jPanel1,BorderLayout.WEST);this.add(jPanel2,BorderLayout.CENTER);this.add(jPanel3,BorderLayout.EAST);JLabel label1 = new JLabel("       读者       ");JLabel label2 = new JLabel("        临界区");JLabel label3 = new JLabel("       写者       ");label1.setFont(new Font("宋体",Font.BOLD,20));label2.setFont(new Font("宋体",Font.BOLD,20));label3.setFont(new Font("宋体",Font.BOLD,20));jPanel1.add(label1,BorderLayout.NORTH);jPanel2.add(label2,BorderLayout.NORTH);jPanel3.add(label3,BorderLayout.NORTH);jTextPane2.setLayout(new FlowLayout(FlowLayout.CENTER));//没起作用jTextPane1.setEditable(false);//禁止编辑jTextPane2.setEditable(false);jTextPane3.setEditable(false);//三个大的文本区域jTextPane1.setFont(new Font("宋体",Font.BOLD,16));jTextPane2.setFont(new Font("宋体",Font.BOLD,16));jTextPane3.setFont(new Font("宋体",Font.BOLD,16));jPanel1.add(new JScrollPane(jTextPane1),BorderLayout.CENTER);jPanel2.add(new JScrollPane(jTextPane2),BorderLayout.CENTER);jPanel3.add(new JScrollPane(jTextPane3),BorderLayout.CENTER);JButton jButton1 = new JButton("加入读者");JButton jButton2 = new JButton("加入写者");jButton1.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {new Thread(new Read(reader)).start();reader++;}});jButton2.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {new Thread(new Write(writer)).start();writer++;}});jPanel1.add(jButton1,BorderLayout.SOUTH);jPanel3.add(jButton2,BorderLayout.SOUTH);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setVisible(true);}public static void insert1(String str)//读模块的gui部分{SimpleAttributeSet set = new SimpleAttributeSet();StyleConstants.setUnderline(set, true);try{jTextPane1.getDocument().insertString(jTextPane1.getDocument().getLength(), str + "\n", set);}catch (BadLocationException e){e.printStackTrace();}}public static void insert2(String str)//被访问文件模块的gui部分{SimpleAttributeSet set = new SimpleAttributeSet();StyleConstants.setUnderline(set, true);try{jTextPane2.getDocument().insertString(jTextPane2.getDocument().getLength(), str + "\n", set);}catch (BadLocationException e){e.printStackTrace();}}public static void insert3(String str)//写模块的gui部分{SimpleAttributeSet set = new SimpleAttributeSet();StyleConstants.setUnderline(set, true);try{jTextPane3.getDocument().insertString(jTextPane3.getDocument().getLength(), str + "\n", set);}catch (BadLocationException e){e.printStackTrace();}}public static void refresh(){jTextPane1.setText(null);jTextPane2.setText(null);jTextPane3.setText(null);for(String a : Re){insert1("读者"+a);}for(String b : ing){insert2(b);}for(String c : Wr){insert3("写者"+c);}}public static void main(String[] args){int a = Integer.parseInt(JOptionPane.showInputDialog("请输入初始读者数量"));int b = Integer.parseInt(JOptionPane.showInputDialog("请输入初始写者数量"));new ReadAndWrite(a,b);
//        new Thread(new Read(1)).start();
//        new Thread(new Read(2)).start();
//        new Thread(new Read(3)).start();
//        new Thread(new Write(1)).start();
//        new Thread(new Write(2)).start();}
}

写者

import java.util.concurrent.Semaphore;import java.util.Random;public class Read extends Thread{private int num;Read(int num){this.num = num;}public void run() {try {synchronized(this){Random random = new Random();wait(random.nextInt(500));ReadAndWrite.insert1("读者"+num+"打算读文件");ReadAndWrite.Re.add(num+"打算读文件");ReadAndWrite.w.acquire();           //实现写有先ReadAndWrite.mutex.acquire();       //防止读者之间同步访问count,读者互斥访问countif(ReadAndWrite.count==0)ReadAndWrite.rw.acquire();      //实现读写互斥ReadAndWrite.count++;               //我只要有东西正在读你,你就不许给我写东西,实现多读者同步的关键ReadAndWrite.mutex.release();ReadAndWrite.w.release();//以下为读文件的阶段ReadAndWrite.insert2("读者"+num+"正在读文件");ReadAndWrite.ing.add("读者"+num+"正在读文件");wait(random.nextInt(5000)+1500);ReadAndWrite.insert2("读者"+num+"结束读文件");ReadAndWrite.insert1("读者"+num+"完成读文件");ReadAndWrite.ing.remove("读者"+num+"正在读文件");ReadAndWrite.Re.remove(num+"打算读文件");//以上为读文件的阶段wait(3000);ReadAndWrite.fresh.acquire();              //实现刷新页面时,线程的互斥ReadAndWrite.refresh();                    //刷新页面,通过队列的信息刷新页面ReadAndWrite.fresh.release();ReadAndWrite.mutex.acquire();ReadAndWrite.count--;                   //文件读完了,读完一个出来一个,count--了if(ReadAndWrite.count==0)ReadAndWrite.rw.release();ReadAndWrite.mutex.release();}} catch (InterruptedException e) {System.out.println("读者"+num+"出现错误!");e.printStackTrace();}}}

读者

import java.util.Random;public class Write extends Thread
{private int num;Write(int num){this.num = num;}public void run(){try{synchronized(this){Random random = new Random();wait(random.nextInt(500));ReadAndWrite.insert3("写者"+num+"打算写文件");ReadAndWrite.Wr.add(num+"打算写文件");ReadAndWrite.w.acquire();ReadAndWrite.rw.acquire();ReadAndWrite.insert2("写者"+num+"正在写文件");ReadAndWrite.ing.add("写者"+num+"正在写文件");wait(random.nextInt(10000)+3000);ReadAndWrite.insert2("写者"+num+"结束写文件");ReadAndWrite.insert3("写者"+num+"完成写文件");ReadAndWrite.ing.remove("写者"+num+"正在写文件");ReadAndWrite.Wr.remove(num+"打算写文件");wait(3000);ReadAndWrite.fresh.acquire();ReadAndWrite.refresh();//刷新页面,通过队列的信息刷新页面ReadAndWrite.fresh.release();ReadAndWrite.rw.release();ReadAndWrite.w.release();}} catch (InterruptedException e){System.out.println("写者"+num+"出现错误!");e.printStackTrace();}}
}

环境:IDEA

 

这篇关于写优先的读者写者问题(Java实现)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/795516

相关文章

HTML5 getUserMedia API网页录音实现指南示例小结

《HTML5getUserMediaAPI网页录音实现指南示例小结》本教程将指导你如何利用这一API,结合WebAudioAPI,实现网页录音功能,从获取音频流到处理和保存录音,整个过程将逐步... 目录1. html5 getUserMedia API简介1.1 API概念与历史1.2 功能与优势1.3

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

springboot项目中整合高德地图的实践

《springboot项目中整合高德地图的实践》:本文主要介绍springboot项目中整合高德地图的实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一:高德开放平台的使用二:创建数据库(我是用的是mysql)三:Springboot所需的依赖(根据你的需求再

spring中的ImportSelector接口示例详解

《spring中的ImportSelector接口示例详解》Spring的ImportSelector接口用于动态选择配置类,实现条件化和模块化配置,关键方法selectImports根据注解信息返回... 目录一、核心作用二、关键方法三、扩展功能四、使用示例五、工作原理六、应用场景七、自定义实现Impor

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

PostgreSQL中MVCC 机制的实现

《PostgreSQL中MVCC机制的实现》本文主要介绍了PostgreSQL中MVCC机制的实现,通过多版本数据存储、快照隔离和事务ID管理实现高并发读写,具有一定的参考价值,感兴趣的可以了解一下... 目录一 MVCC 基本原理python1.1 MVCC 核心概念1.2 与传统锁机制对比二 Postg

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4

一文详解如何在idea中快速搭建一个Spring Boot项目

《一文详解如何在idea中快速搭建一个SpringBoot项目》IntelliJIDEA作为Java开发者的‌首选IDE‌,深度集成SpringBoot支持,可一键生成项目骨架、智能配置依赖,这篇文... 目录前言1、创建项目名称2、勾选需要的依赖3、在setting中检查maven4、编写数据源5、开启热

C++中零拷贝的多种实现方式

《C++中零拷贝的多种实现方式》本文主要介绍了C++中零拷贝的实现示例,旨在在减少数据在内存中的不必要复制,从而提高程序性能、降低内存使用并减少CPU消耗,零拷贝技术通过多种方式实现,下面就来了解一下... 目录一、C++中零拷贝技术的核心概念二、std::string_view 简介三、std::stri