package dong;
public class WaitAndNotify {
public static void main(String[] args) {
// TODO Auto-generated method stub
final Temp temp = new Temp();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 50; i++) {
temp.sub(i);
}
}
}).start();
for (int i = 1; i <= 50; i++) {
temp.main(i);
}
}
}
class Temp {
private boolean flag = true;
public synchronized void main(int j){
if (flag) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int i = 1; i <= 100; i++) {
System.out.println("main=="+j+"==="+i+"===="+Thread.currentThread().getName());
}
flag = true;
// flag = !flag;
notify();
}
public synchronized void sub(int j){
if (!flag) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int i = 1; i <= 10; i++) {
System.out.println("sub++++"+j+"+++++"+i+"++++++++++++"+Thread.currentThread().getName());
}
flag = false;
// flag = !flag;
notify();
}
}
网友评论