为什么此程序只有1个线程在执行?
代码如下:
package demo;
public class AddSubDemo {
public static void main(String[] args) {
Resource resource = new Resource();
new Thread(new AddRunnable(resource)).start();
new Thread(new SubRunnable(resource)).start();
}
}
class AddRunnable implements Runnable {
private Resource resource;
public AddRunnable(Resource resource) {
this.resource = resource;
}
@Override
public void run() {
while (true) {
try {
resource.add();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class SubRunnable implements Runnable {
private Resource resource;
public SubRunnable(Resource resource) {
this.resource = resource;
}
@Override
public void run() {
while (true) {
try {
resource.sub();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Resource {
private int num = 0;
private boolean flag = true; // true:执行ADD;false:执行SUB
public synchronized void add() throws InterruptedException {
if (this.flag = false) {
super.wait();
}
Thread.sleep(1000);
this.num++;
flag = false;
System.out.println(Thread.currentThread().getName() + " " + this.num);
super.notifyAll();
}
public synchronized void sub() throws InterruptedException {
if (this.flag == true) {
super.wait();
}
Thread.sleep(2000);
this.num--;
flag = true;
System.out.println(Thread.currentThread().getName() + " " + this.num);
super.notifyAll();
}
}
日志如下:
Thread-0:1
Thread-0:2
Thread-0:3
Thread-0:4
Thread-0:5
Thread-0:6
Thread-0:7