*****************************************Stor.java************************************************
package com.gem.lesson10.adddec;
class Stor {
private final int Max_Size = 10;
private final int Min_Size = 0;
private int i = 8;
public Stor(){}
public Stor(int cur) {
this.i = cur;
}
public synchronized void add(){
if(this.i >= this.Max_Size){
System.out.println("当前值: " + this.i + "\t将超出最大值,无法自增!");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.i++;
System.out.println("已完成自加。当前值: " + this.i);
notifyAll();
}
public synchronized void dec(){
if(this.i <= this.Min_Size){
System.out.println("当前值: " + this.i + "\t将超出最大值,无法自增!");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.i--;
System.out.println("已完成自减。当前值: " + this.i);
notifyAll();
}
}
*****************************************Add.java************************************************
package com.gem.lesson10.adddec;
public class Add extends Thread{
private Stor stor;
Add(){}
Add(Stor stor){
this.stor = stor;
}
public void run() {
this.stor.add();
}
}
*****************************************Dec.java************************************************
package com.gem.lesson10.adddec;
public class Dec extends Thread{
private Stor stor;
Dec(){}
Dec(Stor stor){
this.stor = stor;
}
public void run() {
this.stor.dec();
}
}
*****************************************Adddec.java**********************************************
package com.gem.lesson10.adddec;
public class Adddec{
public static void main(String[] args) {
Stor stor = new Stor(5);
Add a1 = new Add(stor);
Add a2 = new Add(stor);
Add a3 = new Add(stor);
Add a4 = new Add(stor);
Dec d1 = new Dec(stor);
Dec d2 = new Dec(stor);
Dec d3 = new Dec(stor);
Dec d4 = new Dec(stor);
a1.start();
a2.start();
a3.start();
a4.start();
d1.start();
d2.start();
d3.start();
d4.start();
}
}