</pre><pre name="code" class="java">// java 线程同步
// zhangsan 和 lisi 同用一个厕所,张三先刷牙,张三等待,李四刷牙,李四等待,张三小便,张三等待,李四小便。<pre name="code" class="java">package TestPacage;
public class SynchronizationTest {
public static void main(String [] args){
MyRoomThread.zhangsan.start();
MyRoomThread.lisi.start();
//MyRoomThread.lisi
}
}
class MyRoomThread extends Thread{
static MyRoomThread zhangsan= new MyRoomThread("zhangsan");
static MyRoomThread lisi=new MyRoomThread("lisi");
private String name;
static Object toliet=new Object();
MyRoomThread(String name){
this.name=name;
}
@Override
public void run() {
// TODO Auto-generated method stub
//super.run();
try{
synchronized(toliet){
if(this.name.equals("zhangsan")){
this.brush();
toliet.wait();
this.pee();
toliet.notify();
}
else{
this.brush();
toliet.notify();
toliet.wait();
this.pee();
}
}
}
catch(Exception e){
System.out.print(e);
}
}
public void brush() throws Exception {
System.out.println(this.name +"brushing");
Thread.sleep(2000);
System.out.println(this.name +"brushed");
}
public void pee() throws Exception {
System.out.println(this.name +"peeing");
Thread.sleep(2000);
System.out.println(this.name +"peed");
}
}