資源簡介
實現一個數據單元,包括學號和姓名兩部分。編寫兩個線程,一個線程往數據單元中寫,另一個線程往出讀。要求每寫一次就往出讀一次。

代碼片段和文件信息
import?java.io.*;
class?Student{
String?id;
String?name;
int?number=0;
BufferedReader?writer=new?BufferedReader(new?InputStreamReader(System.in));?
boolean?available=false;//是否有學生信息可寫
public?Student(){
this(“?““?“);
}
public?Student(String?idString?name){
this.id=id;
this.name=name;
}
public?synchronized?void?write1Info(){
if(available)
try{
wait();
}
catch(Exception?e){
}
System.out.println(“請輸入第“+(++number)+“個學生的信息“);
System.out.print(“請輸入學號:“);
try{
id=writer.readLine();
}
catch(Exception?e){
System.out.println(“輸入學號出錯!“);
}
System.out.print(“請輸入姓名:“);
try{
name=writer.readLine();
}
catch(Exception?e)
{
System.out.println(“輸入姓名出錯“);
}
available=true;
notify();
}
public?synchronized?void?readInfo(){
if(!available)
try{
wait();
}
catch(Exception?e){
}
System.out.println(“讀出第“+(number)+“個學生的信息“);
System.out.println(“學號:?“+id+“???姓名:?“+name);
System.out.println();
available=false;
notify();
}
}
class?Writer?extends?Thread{
Student?s=null;
public?Writer(Student?s){
this.s=s;
}
public?void?run(){
while(true){
s.write1Info();
}
}
}
class?Reader?extends?Thread{
Student?s=null;
public?Reader(Student?s)
{
this.s=s;
}
public?void?run(){
while(true){
s.readInfo();
}
}
}
public?class?TestThread?{
public?static?void?main(String[]?args)?{
//?TODO?Auto-generated?method?stub
Student?s=new?Student();
new?Writer(s).start();
new?Reader(s).start();
}
}
?屬性????????????大小?????日期????時間???名稱
-----------?---------??----------?-----??----
?????文件????????397??2010-04-28?13:35??實驗四\.project
?????文件????????232??2010-04-28?13:35??實驗四\.classpath
?????文件???????1658??2010-05-04?19:33??實驗四\src\TestThread.java
?????文件????????536??2010-05-04?19:33??實驗四\bin\TestThread.class
?????文件????????438??2010-05-04?19:33??實驗四\bin\Reader.class
?????文件???????1964??2010-05-04?19:33??實驗四\bin\Student.class
?????文件????????440??2010-05-04?19:33??實驗四\bin\Writer.class
?????目錄??????????0??2010-05-08?22:59??實驗四\src
?????目錄??????????0??2010-05-08?22:59??實驗四\bin
?????目錄??????????0??2010-05-08?22:59??實驗四
-----------?---------??----------?-----??----
?????????????????5665????????????????????10
- 上一篇:ADXL362例程
- 下一篇:基于Fisher的人臉識別程序
評論
共有 條評論