此程序为什么只有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
代码写错了
if (this.flag = false) >> if (this.flag == false)
就好了
第 1 个线程占用了 Resource 对象锁没释放,第 2 个线程被阻塞在 resource.sub() 等待获取对象锁。
学习........................