資源簡介
進程同步的模擬與實現
閱覽室讀書問題:假定一個閱覽室最多可容納100
人,讀者進入和離開閱覽室時都必須在閱覽室門
口的一個登記表上進行登記,而且每次只允許一
人進行登記操作。請用信號量實現上述進程的同
步問題。
代碼片段和文件信息
package?hair;
import?java.awt.Color;
import?java.awt.Container;
import?java.util.Random;
import?java.util.concurrent.Semaphore;
import?javax.swing.*;
public?class?ReadingRoom?extends?Jframe{
/**
?*?
?*/
private?static?final?long?serialVersionUID?=?1L;
static?int?readers?=?0;//讀者人數
static?int?seats?=?5;//閱覽室的空座位數,初值為5
static?Semaphore?mutex?=?new?Semaphore(1);//互斥信號量,初值為1
boolean?regist=true;
static?Sofa?j1;
static?Sofa?j2;
static?Sofa?j3?;
static?Sofa?j4?;
static?Sofa?j5;
static?Sofa?j6;
static?Sofa?j7;
static?Sofa?j8?;
static?Sofa?j9?;
static?Sofa?j10;
static?JButton?j?;
????static?Sofa[]?sofas;
public?ReadingRoom(){
Container?c?=?getContentPane();
setBounds(550?240?600?600);
setLayout(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
settitle(“圖書閱覽室“);
????j1?=?new?Sofa(“空閑“);
j2?=?new?Sofa(“空閑“);
j3?=?new?Sofa(“空閑“);
j4?=?new?Sofa(“空閑“);
j5?=?new?Sofa(“空閑“);
j6?=?new?Sofa(“空閑“);
j7?=?new?Sofa(“空閑“);
j8?=?new?Sofa(“空閑“);
j9?=?new?Sofa(“空閑“);
j10?=?new?Sofa(“空閑“);
j?=?new?Sofa(“登記處“);
j1.setBounds(20?300?80?60);
j2.setBounds(110?300?80?60);
j3.setBounds(200?300?80?60);
j4.setBounds(290?300?80?60);
j5.setBounds(380?300?80?60);
j6.setBounds(20?400?80?60);
j7.setBounds(110?400?80?60);
j8.setBounds(200?400?80?60);
j9.setBounds(290?400?80?60);
j10.setBounds(380?400?80?60);
j.setBounds(160?50?150?100);
c.add(j1);
c.add(j2);
c.add(j3);
c.add(j4);
c.add(j5);
c.add(j6);
c.add(j7);
c.add(j8);
c.add(j9);
c.add(j10);
c.add(j);
????sofas?=?new?Sofa[]{j1j2j3j4j5j6j7j8j9j10};
}
public?void?open(){
while(true){
try?{
Thread.sleep((long)?(Math.random()*5000));
}?catch?(InterruptedException?e)?{
e.printStackTrace();
}
new?Thread(new?Reader(createName())).start();
}
}
public?static?void?main(String?args[])?throws?InterruptedException?{
ReadingRoom?rr?=?new?ReadingRoom();
rr.open();
}
/*
?*?判斷閱覽室座位是否為滿
?*/
public?synchronized?static?boolean?isFull()?{
if?(readers?==?seats)?{
return?true;
}
return?false;
}
/*
?*?讀者進入閱覽室
- 上一篇:方立勛30天Javaweb視頻
- 下一篇:用JSP做的圖書館管理系統
評論
共有 條評論