publicclassTestThread{privateint j;publicstaticvoidmain(String[] args){// TODO Auto-generated method stub
TestThread testThread =newTestThread();
Add add = testThread.newAdd();
Minus minus = testThread.newMinus();for(int i =0; i <2; i++){newThread(add).start();newThread(minus).start();}}//增加类privateclassAddimplementsRunnable{@Overridepublicvoidrun(){for(int i =0; i <100; i++){add();}}}//减少类privateclassMinusimplementsRunnable{@Overridepublicvoidrun(){for(int i =0; i <100; i++){minus();}}}//增加方法privatesynchronizedvoidadd(){
j++;
System.out.println(Thread.currentThread().getName()+" add 结果:"+ j);}//减少方法privatesynchronizedvoidminus(){
j--;
System.out.println(Thread.currentThread().getName()+" minus 结果:"+ j);}}
把j的值控制在0-100之间浮动
publicclassTestThread{privateint j;publicstaticvoidmain(String[] args){// TODO Auto-generated method stub
TestThread testThread =newTestThread();
Add add = testThread.newAdd();
Minus minus = testThread.newMinus();for(int i =0; i <2; i++){newThread(add).start();newThread(minus).start();}}//增加类privateclassAddimplementsRunnable{@Overridepublicvoidrun(){for(int i =0; i <100; i++){try{add();}catch(InterruptedException e){
e.printStackTrace();}}}}//减少类privateclassMinusimplementsRunnable{@Overridepublicvoidrun(){for(int i =0; i <100; i++){try{minus();}catch(InterruptedException e){
e.printStackTrace();}}}}//增加方法privatesynchronizedvoidadd()throws InterruptedException {if(j <100){
j++;
System.out.println(Thread.currentThread().getName()+" add 结果 "+ j);this.notify();//开始}else{this.wait();//等待}}//减少方法privatesynchronizedvoidminus()throws InterruptedException {if(j >0){
j--;
System.out.println(Thread.currentThread().getName()+" minus 结果 "+ j);this.notify();//开始}else{this.wait();//等待}}}