线程交替题目
2018-09-20 本文已影响22人
咚了个汐
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();
}
}