编写一个多线程程序,实现这样一个目标:
①存在一个对象,该对象有一个int类型的成员变量counter,该成员变量的初始值为0.
②创建四个线程,其中两个线程对该对象的成员变量counter加1,另外两个线程对该对象的成员变量减1.
③输出该对象成员变量counter每次变化后的值。
④最终输出的结果为:1010101010...
public class MyObject { private int counter; public synchronized void increase() { while (counter == 1) { try { wait(); } catch (InterruptedException ex) { ex.printStackTrace(); } } counter++; System.out.println(counter); notify(); } public synchronized void decrease() { while (counter == 0) { try { wait(); } catch (InterruptedException ex) { ex.printStackTrace(); } } counter--; System.out.println(counter); notify(); } }
public class DecreaseThread extends Thread { private MyObject myObject; public DecreaseThread(MyObject myObject) { this.myObject = myObject; } @Override public void run() { for (int i = 0; i < 10; ++i) { try { Thread.sleep((long)(Math.random() * 1000)); } catch (InterruptedException ex) { ex.printStackTrace(); } myObject.decrease(); } } }
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 ex) { ex.printStackTrace(); } myObject.increase(); } } }
public class Client { public static void main(String[] args) { MyObject myObject = new MyObject(); Thread increaseThread = new IncreaseThread(myObject); Thread increaseThread2 = new IncreaseThread(myObject); Thread decreaseThread = new DecreaseThread(myObject); Thread decreaseThread2 = new DecreaseThread(myObject); increaseThread.start(); increaseThread2.start(); decreaseThread.start(); decreaseThread2.start(); } }