学习多线程时,想写一个取球放球的代码,然后想要循环这个操作10次,但是最终只执行了1次。
以i++模拟放球,i--模拟取球
public class SyncTest {
private static int i=0;
static class Thread1 implements Runnable{
@Override
public void run() {
for (int a=0;a<10;a++){
synchronized(this){
if (i > 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
i++;
notify();
System.out.println(i);
}
}
}
}
static class Thread2 implements Runnable{
@Override
public void run() {
for (int a=0;a<10;a++) {
synchronized (this) {
if (i == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
i--;
notify();
System.out.println(i);
}
}
}
}
public static void main(String[] args) {
new Thread(new Thread1()).start();
new Thread(new Thread2()).start();
}
}
debug后发现两个线程都wait了。如果不在线程这两个线程终做循环,而是在主线程去循环创建线程可以达到效果,但是一直创建和销毁线程又不太好。
有什么更好的方法吗