java模擬哲學家就餐問題

廢話很少說 直接上代碼java

1.筷子類 他有兩個屬性, 一個是標示這根筷子在哪一個哲學家手邊,另外一個屬性標示這個筷子的狀態,而且這個狀態是隨時從內存當中取出的數組

package com.bjs.dinning;

public class Chopstick {
	/**
	 * 表示筷子是否可用
	 * */
	private volatile boolean available = true;

	private int id;

	public Chopstick() {

	}

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

	public int getId() {
		return id;
	}

	public boolean isAvailable() {
		return available;
	}

	public void setAvailable(boolean available) {
		this.available = available;
	}

	public void setId(int id) {
		this.id = id;
	}
	@Override
	public String toString() {
		return "筷子" + id;
	}
}

2.筷子數組  動態決定幾個哲學家 幾根筷子dom

package com.bjs.dinning;

public class ChopstickArray {
	private Chopstick[] chopsticks;

	public ChopstickArray() {

	}

	public ChopstickArray(int size) {
		chopsticks = new Chopstick[size];
		for (int i = 0; i < chopsticks.length; ++i) {
			chopsticks[i] = new Chopstick(i);
		}
	}

	public Chopstick getId(int id) {
		return chopsticks[id];
	}

	public Chopstick getLast(int id) {
		if (id == 0) {
			return chopsticks[chopsticks.length - 1];
		} else {
			return chopsticks[id - 1];
		}
	}
}

3.哲學家類ide

package com.bjs.dinning;

import java.util.Random;

import javax.swing.JTextArea;

public class Philosopher implements Runnable {

	ChopstickArray chopstickArray;

	JTextArea eatingTextArea;

	private int id;

	private boolean state;

	JTextArea thinkingTextArea;

	JTextArea waitingTextArea;

	public Philosopher() {

	}
	public Philosopher(int id, ChopstickArray chopstickArray,
			JTextArea thinkingTextArea, JTextArea eatingtextArea,
			JTextArea waitingTextArea) {
		this.id = id;
		this.chopstickArray = chopstickArray;
		this.thinkingTextArea = thinkingTextArea;
		this.eatingTextArea = eatingtextArea;
		this.waitingTextArea = waitingTextArea;
	}
	public synchronized void eating() {
		if (!state) { // 在思考
			if (chopstickArray.getId(id).isAvailable()) { // 若是哲學家右手邊的筷子可用
				if (chopstickArray.getLast(id).isAvailable()) { // 若是左手邊的筷子也可用
					// 而後將這個能吃飯的哲學家兩側的筷子都設置爲不可用
					chopstickArray.getId(id).setAvailable(false);
					chopstickArray.getLast(id).setAvailable(false);
					String text = eatingTextArea.getText();
					eatingTextArea.setText(text + this + "在吃飯\n");
					try {
						Thread.sleep(1000);
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					// 右手邊的筷子可用,可是左手邊的不可用
					String str = waitingTextArea.getText();
					waitingTextArea.setText(str + this + "在等待"
							+ chopstickArray.getLast(id) + "\n");
					try {
						wait(new Random().nextInt(100));
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			} else {
				// 若是哲學家右手邊的筷子不可用則等待
				String str = waitingTextArea.getText();
				waitingTextArea.setText(str + this + "在等待"
						+ chopstickArray.getId(id) + "\n");
				try {
					wait(new Random().nextInt(100));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		state = true;
	}
	@Override
	public void run() {
		for (int i = 0; i < 10; ++i) {
			thinking();
			eating();
		}
	}
	public synchronized void thinking() {
		if (state) { // 若是在思考,說明這個哲學家兩面的筷子沒用
			chopstickArray.getId(id).setAvailable(true);
			chopstickArray.getLast(id).setAvailable(true);
			String text = thinkingTextArea.getText();
			thinkingTextArea.setText(text + this + "在思考\n");
			try {
				Thread.sleep(1000);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		state = false;
	}
	@Override
	public String toString() {
		return " 哲學家 " + id;
	}

}

4.運行的入口類 this

package com.bjs.dinning;

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
 
public class DiningPhilosophersFrame extends JFrame{
    public DiningPhilosophersFrame(){
        panel2.setLayout(new GridLayout(2, 2, 3, 3));
        panel2.add(label2);
        panel2.add(label3);
        panel2.add(label4);
        JScrollPane js1 = new JScrollPane(thinkingTextArea,
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        JScrollPane js2 = new JScrollPane(eatingTextArea,
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        JScrollPane js3 = new JScrollPane(waitingTextArea,
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        panel2.add(js1);
        panel2.add(js2);
        panel2.add(js3);
        panel1.setLayout(new FlowLayout());
        panel1.add(label1);
        panel1.add(panel2);
        panel1.add(button);
        setContentPane(panel1);
        button.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e){
                ChopstickArray chopstickArray = new ChopstickArray(3);
                for(int i = 0; i < 3; i++){
                    new Thread(new Philosopher(i, chopstickArray,
                            thinkingTextArea, eatingTextArea, waitingTextArea))
                            .start();
                }
            }
        });
 
        setSize(300, 400);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
 
    public static void main(String[] args){
        new DiningPhilosophersFrame();
    }
 
    private final JPanel panel1 = new JPanel();
    private final JPanel panel2 = new JPanel();
 
    private final JTextArea thinkingTextArea = new JTextArea(5, 10);
    private final JTextArea eatingTextArea = new JTextArea(5, 10);
    private final JTextArea waitingTextArea = new JTextArea(5, 10);
 
    JLabel label1 = new JLabel("哲學家問題");
    JLabel label2 = new JLabel("思考");
    JLabel label3 = new JLabel("吃飯");
    JLabel label4 = new JLabel("等待");
 
    JButton button = new JButton("開始運行");
}
相關文章
相關標籤/搜索