package com.tju; class Target { private int count; public synchronized void increase() { if(count == 2) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } count++; System.out.println(Thread.currentThread().getName() + ":" + count); notify(); } public synchronized void decrease() { if(count == 0) { try { //等待,由於Decrease線程調用的該方法, //URL:http://www.bianceng.cn/Programming/Java/201608/50397.htm //所以Decrease線程進入對象t(main函數中實例化的)的等待池,並且釋放對象t的鎖 wait();//Object類的方法 } catch (InterruptedException e) { e.printStackTrace(); } } count--; System.out.println(Thread.currentThread().getName() + ":" + count); //喚醒線程Increase,Increase線程從等待池到鎖池 notify(); } } class Increase extends Thread { private Target t; public Increase(Target t) { this.t = t; } @Override public void run() { for(int i = 0 ;i < 30; i++) { try { Thread.sleep((long)(Math.random()*500)); } catch (InterruptedException e) { e.printStackTrace(); } t.increase(); } } } class Decrease extends Thread { private Target t; public Decrease(Target t) { this.t = t; } @Override public void run() { for(int i = 0 ; i < 30 ; i++) { try { //隨機睡眠0~500毫秒 //sleep方法的調用,不會釋放對象t的鎖 Thread.sleep((long)(Math.random()*500)); } catch (InterruptedException e) { e.printStackTrace(); } t.decrease(); } } } public class Test { public static void main(String[] args) { Target t = new Target(); Thread t1 = new Increase(t); t1.setName("Increase"); Thread t2 = new Decrease(t); t2.setName("Decrease"); t1.start(); t2.start(); } }