class TestThread
{
public static void main(String[] args)
{
Data dd = new Data();
T1 t1 = new T1(dd);
T2 t2 = new T2(dd);
t1.start();
t2.start();
}
};
class Data
{
char c;
boolean flag;
};
class T1 extends Thread
{
Data d;
public T1(Data d)
{
this.d = d; //此处前面的this.d可以省略掉this
}
public void run()
{
for (int i = 0;i < 20 ;i++ )
{
synchronized(d)
{
while (d.flag)
{
try
{
d.wait();
}
catch (Exception error)
{
}
}
d.c = (char)('A' + (int)(Math.random()*26));
d.flag = true;
System.out.println("产生: " + d.c);
d.notify(); //此处用d.notifyAll();可以唤醒等待的所有线程
}
try
{
Thread.sleep((int)(Math.random()*1000));
}
catch (Exception error)
{
}
}
}
};
class T2 extends Thread
{
Data d;
public T2(Data d)
{
this.d = d;
}
public void run()
{
for (int i = 0;i < 20 ;i++ )
{
synchronized(d)
{
while (!d.flag)
{
try
{
d.wait();
}
catch (Exception error)
{
}
}
System.out.println("产生: " + d.c);
d.flag = false;
d.notify(); //此处用d.notifyAll();可以唤醒等待的所有线程
}
try
{
Thread.sleep((int)(Math.random()*1000));
}
catch (Exception error)
{
}
}
}
};