1、MyObject
public class MyObject { private int counter; public synchronized void increase(){ if (counter != 0) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } counter++; System.out.print(counter); notify(); } public synchronized void decrease(){ if(counter == 0) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } counter--; System.out.print(counter); notify(); } }
2、IncreaseThread
public class IncreaseThread extends Thread { private MyObject myObject; public IncreaseThread(MyObject myObject) { this.myObject = myObject; } @Override public void run(){ for (int i = 0; i < 30; i++) { try { Thread.sleep((long) (Math.random() * 1000)); } catch (InterruptedException e) { e.printStackTrace(); } myObject.increase(); } } }
3、DecreaseThread
public class DecreaseThread extends Thread { private MyObject myObject; public DecreaseThread(MyObject myObject) { this.myObject = myObject; } @Override public void run() { for (int i = 0; i < 30; i++) { try { Thread.sleep((long)(Math.random() * 1000)); } catch (InterruptedException e) { e.printStackTrace(); } myObject.decrease(); } } }
4、测试类
public class MyTest { public static void main(String [] args) { MyObject myObject = new MyObject(); IncreaseThread increaseThread = new IncreaseThread(myObject); DecreaseThread decreaseThread = new DecreaseThread(myObject); increaseThread.start(); decreaseThread.start(); } }
// 输出结果:
101010101010101010101010101010101010101010101010101010101010
5、扩展
如果两个增的线程,两个减的线程,需要将MyObject类中的方法,if判断改为while