银行家算法的java模拟实现

import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.Security;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

import org.omg.CORBA.PUBLIC_MEMBER;

public class bank extends JFrame implements ActionListener {

    private JTable table;
    private JPanel jPanel;
    private JTextField text[];
    private JButton b1, b2, b3;
    private DefaultTableModel tableModel;
    private JScrollPane jscrollpane;
    int[] temp = new int[10];
    int start;
    long starTime = System.currentTimeMillis();
    long endTime = System.currentTimeMillis();
    private int[] resource, time;
    private int num;

    String[] column1 = { "进程", "A", "B", "C", "D", "E", "E", "G", "H" };

    public bank() {
        

        this.setSize(1000, 400);
        this.setTitle("银行家算法");
        JPanel panel = new JPanel();
        this.getContentPane().add(panel, "South");

        final int[] avaliable = new int[4];
        this.resource = new int[1000];
        this.time = new int[1000];
        this.num = 0;
        
        String str[] = { "进程个数", "资源个数","A", "B", "C", "D","E" };
        String str_text[] = { "", "","","","","",""};
        
        this.text = new JTextField[str_text.length];
        for (int i = 0; i < str_text.length; i++) {
            panel.add(new JLabel(str[i]));
            text[i] = new JTextField(str_text[i], 5);
            panel.add(text[i]);
        }
        b1 = new JButton("增加");
        panel.add(b1);
        b1.addActionListener(this);

        b2 = new JButton("提交");
        panel.add(b2);

        b3 = new JButton("统计图");
        panel.add(b3);

        JPanel pan = new JPanel();
        this.getContentPane().add(pan, "North");
        pan.add(new JLabel("process                          "));
        pan.add(new JLabel("                         Allocation"));

        this.tableModel = new DefaultTableModel(column1, 0);
        JTable jTable = new JTable(this.tableModel);
        this.getContentPane().add(new JScrollPane(jTable));
        this.setVisible(true);
    
        

        b2.addActionListener(new ActionListener() { // 对资源进行提交

            public void actionPerformed(ActionEvent e) {
                int row = Integer.parseInt(text[0].getText()); // 当前系统中进程的个数
                int column = Integer.parseInt(text[1].getText());
                
                for (int i = 0; i < column; i++) {
                    avaliable[i] = Integer.parseInt(text[i + 2].getText()); // 获取当前可用资源
                }
                int[][] max = new int[row][column];
                int[][] Allocation = new int[row][column];
                int[][] need = new int[row][column];
                    
                for (int j = 0; j < row; j++) // 获取每个进程的最大需求
                {
                    for (int i = 0; i < column; i++) {
                        int temp = Integer.parseInt(tableModel.getValueAt(j, i + 1).toString());
                        max[j][i] = temp;
                        // System.out.print(max[j][i]+" ");
                    }
                    // System.out.print("\n");
                }
                for (int j = 0; j < row; j++) // 获取每个进程的已分配资源数目
                {
                    for (int i = column; i < 2 * column; i++) {
                        int temp = Integer.parseInt(tableModel.getValueAt(j, i + 1).toString());
                        Allocation[j][i - column] = temp;
                        // System.out.print(Allocation[j][i-column]+" ");
                    }
                    // System.out.print("\n");
                }
                int m = 0;
                for (int j = 0; j < row; j++) // 获取每个进程仍需资源数目
                {
                    for (int i = 0; i < column; i++) {
                        need[j][i] = max[j][i] - Allocation[j][i];
                        if (need[j][i] < 0)
                            m++;
                    }
                }
                
                if (m > 0)
                    JOptionPane.showMessageDialog(null, "进程分配资源不合理");
                else {
                    if (!this.judge(0, need, avaliable)) {

                        JOptionPane.showMessageDialog(null, "资源分配失败");
                    } else {
                        starTime = System.currentTimeMillis();
                        if (safecheck(start, Allocation, need)) {
                            for (int i = 0; i < row; i++) {
                                // System.out.print(temp[i]+"\n");
                            }
                            String str = "";
                            for (int i = 0; i < row; i++) {
                                System.out.print(temp[i] + "\n");
                                str += tableModel.getValueAt(temp[i], 0);
                                str += " ";
                            }

                            JOptionPane.showMessageDialog(null, "资源分配成功,资源分配序列为:" + str);
                        } else {
                            JOptionPane.showMessageDialog(null, "资源分配失败");
                        }
                    }
                    long endTime = System.nanoTime();
                    long wholeTime = (endTime - starTime) % 1000;
                
                    //System.out.println("程序运行时间:" + wholeTime + "ms");
                    try {

                        String content = column + "\n" + wholeTime + "\n";

                        File file = new File("add.txt");

                        if (!file.exists()) {

                            file.createNewFile();

                        }

                        FileWriter fileWritter = new FileWriter(file.getName(), true);

                        BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
                        bufferWritter.write("\n");
                        bufferWritter.write(content);

                        bufferWritter.close();

                        System.out.println("finish");

                    } catch (IOException e1) {

                        e1.printStackTrace();

                    }

                }
            }

            private boolean judge(int i, int[][] need, int[] a) {
                int row = Integer.parseInt(text[0].getText());
                int column = Integer.parseInt(text[1].getText());
                boolean choice = false;
                int k;

                for (int n = i; n < row; n++) {
                    k = 0;
                    for (int j = 0; j < column; j++) {
                        if (need[n][j] <= a[j])
                            k++;
                    }
                    if (k == column) {
                        start = n;
                        choice = true;
                    }
                }
                System.out.print(start);
                return choice;
            }

            public boolean safecheck(int p, int[][] Allocation, int[][] need) // 算法检查
            {
                int k = 0;
                int row = Integer.parseInt(text[0].getText()); // 进程个数
                int column = Integer.parseInt(text[1].getText());
                boolean b = true; // 资源种类
                boolean[] security = new boolean[row]; // 安全线程的数组
                for (int i = 0; i < row; i++)
                    security[i] = false;
                temp[k++] = p;
                int[] work = new int[column]; // 工作向量
                for (int i = 0; i < column; i++) // 释放资源
                    work[i] = avaliable[i] + Allocation[p][i];

                security[p] = true;

                boolean found = false; // 是否找到安全序列
                while (k < row) {
                    boolean flag = true; // 标记是否有足够资源
                    for (int i = 0; i < row; i++) {
                        if (security[i])
                            continue; // 跳过本次循环体中余下尚未执行的语句,立即进行下一次的循环条件判定
                        for (int j = 0; j < column; j++) {
                            if (need[i][j] > work[j]) // 资源不足,退出
                            {
                                flag = false;
                                break; // 终止本层循环体
                            }
                        }

                        if (flag) // 找到资源
                        {
                            temp[k++] = i;
                            System.out.print(i + "succcess");
                            security[i] = true;
                            found = true;
                            for (int j = 0; j < column; j++)// 释放资源
                            {
                                work[j] = work[j] + Allocation[i][j];
                                System.out.print(work[j] + " ");
                            }
                            System.out.print("\n");
                        }
                    }
                    if (found) {
                        found = false;
                    } else
                        break; // 遍历,试分配失败跳出

                    for (int i = 0; i < row; i++) { // 若存在false,则跳出
                        if (!security[i]) {
                            System.out.print(i + "false");
                            b = false;
                            break;
                        }
                    }
                }
                return b;
            }
        });

        b3.addActionListener(new ActionListener() {
            public void actionPerformed (ActionEvent e) {
                
                File file = new File("add.txt");
                int[] r = null;
                int[] t = null;
                try {
                    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));// 构造一个BufferedReader类来读取文件

                    while ((br.readLine()) != null) {// 使用readLine方法,一次读一行

                        resource[num]=Integer.parseInt(br.readLine());
                        time[num]=Integer.parseInt(br.readLine());
                        num++;
                        //System.out.print(resource[num-1]+" "+time[num-1]+"\n");
                        
                    }
                
                    br.close();
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
                try {
                    new CreateJFreeChart(resource, time);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                File file2 =new File("1.jpg");
                try{
                    java.awt.Desktop.getDesktop().open(file2);
                }catch (Exception e1) {
                    e1.printStackTrace();
                }
                
                
            }
        });
        
    }

    public void actionPerformed(ActionEvent e) {
        try {
            int row = Integer.parseInt(text[0].getText());
            int column = 2 * Integer.parseInt(text[1].getText()) + 1;
            this.tableModel.setRowCount(row);
            this.tableModel.setColumnCount(column);
        } catch (Exception e1) {
            JOptionPane.showMessageDialog(null, "输入为空");
        }

    }

    public static void main(String[] args) throws IOException {
        new bank();

    }

}

实现效果:

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值