package cn.itcast.demo;
/*
* 有两个线程,一个子线程,一个主线程,主线程先运行十次,然后子线程运行100次,如此循环进行五十次
*
*
*
*/
public class TraditionalThreadCommunicationDemo {
public static void main(String[] args) {
final Bussiness bussiness = new Bussiness();
new Thread(new Runnable(){
public void run() {
for (int i = 0; i < 50; i++) {
bussiness.sub();
}
}
}).start();
for (int j = 0; j < 50; j++) {
bussiness.main();
}
}
}
class Bussiness{
private boolean flag = true;
/*
*
* 这个例子同步锁定的对象是这个类本身,即this
*/
public synchronized void main()
{
while/*if*/(flag)
{
for (int i = 0; i < 10; i++) {
System.out.println("this is main of " + i);
}
flag = false;
//唤起在此对象监视器的那个对象
this.notify();
}
try {
//让当前的等待,知道其他对象调用此对象的notify方法或notifyAll()方法
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized void sub()
{
/*
* 有时候一种叫做伪唤醒的情况,这时候如果用if就不会再判断了,就会往下运行,这时候就可能会出错
* 但是如果用while就算是出现伪唤醒还是会去判断就不会出错。这里用while体现了你的水平
*/
while/*if*/(!flag)
{
for (int i = 0; i < 100; i++) {
System.out.println("this is sub of " + i);
}
flag = true;
this.notify();
}
try {
this.wait();//这里等待,知道被唤醒,被唤醒的时候其实就是回到了这行代码这里
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}