创建一个设置的线程类:
public class SetThread implements Runnable {
private StudentDemo s;
private int x = 0;
public SetThread(StudentDemo s)
{
this.s = s;
}
@Override
public void run() {
while(true)
{
synchronized(s)//要用同一把锁!
{
//这里使用等待唤醒机制,使得线程能够依次运行!
if(s.flag)
{
try {
s.wait();
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
if(x%2 == 0)
{
s.name = "zhangsan";
s.age = 21;
}else
{
s.name = "lisi";
s.age = 18;
}
x++;
s.flag = true;
s.notify();
}
}
}
}