Greetings2016
2016-02-28 12:49初学java多线程 遇到点问题望各位前辈不吝赐教
/*张三先洗漱,然后让李四洗漱 李四洗刷完让张三上厕所 张三上完厕所 让李四上厕所
**/
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();
}
}
- 点赞
- 回答
- 收藏
- 复制链接分享
3条回答
为你推荐
- 初学java多线程 遇到点问题望各位前辈不吝赐教
- java
- 多线程
- 3个回答