/*张三先洗漱,然后让李四洗漱 李四洗刷完让张三上厕所 张三上完厕所 让李四上厕所
**/
static MyRoomThread zhangsan = new MyRoomThread("张三");
static MyRoomThread lisi = new MyRoomThread("李四");
String name ;
Object toliet = new Object();
MyRoomThread(String name) {
this.name = name;
}
@Override
public void run() {
try {
synchronized (toliet) {
if (this.name.equals("张三")) {
this.Brush();
toliet.wait();
this.release();
toliet.notify();
}else {
this.Brush();
toliet.wait();;
toliet.notify();
this.release();
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
//洗漱的方法
public void Brush() throws Exception {
System.out.println(this.name+"上厕所,刷牙ing。。。");
Thread.sleep(2000);
System.out.println(this.name+"刷牙完毕,离开厕所。。。");
}
//上厕所的方法
public void release() throws Exception {
System.out.println(this.name+"在上厕所,正在小便ing。。。");
Thread.sleep(2000);
System.out.println(this.name+"小便完毕,离开厕所");
}
}
public >
public static void main(String[] args) {
MyRoomThread.zhangsan.start();
MyRoomThread.lisi.start();
}
}