答:
用了三个宿舍,还是有一定瑕疵,但是写文件,互斥基本解决了 (主要针对第三问)
package pt;
import java.awt.print.Printable;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.Box.Filler;
public class practice implements Runnable{
private int num = 0;
@Override
public void run() {
for(int i=0; i<40; i++){
live();
}
}
public void live(){
try {
File file = new File("employ.text");
if(!file.exists()) {
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(file.getName(),true);
try {
Thread.sleep(300); //休息300毫秒
} catch (InterruptedException e) {
e.printStackTrace();
}
if(this.num<=80){
//打印买票信息
System.out.println(Thread.currentThread().getName() + "入住id: " + this.num++);
fileWriter.write(Thread.currentThread().getName() + "入住id: " + this.num++);
fileWriter.close();
}
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
public static void main(String[] args) {
practice ticketThread = new practice();
new Thread(ticketThread,"宿舍1").start(); //线程一
new Thread(ticketThread,"宿舍2").start(); //线程一
new Thread(ticketThread,"宿舍3").start(); //线程一
}
}