案例说明:
两个线程同时操作一个数,一个线程操作加,另一个线程操作减:
package com.My.Schedule_test.demo.ConPro;
public class zongjie{
static int r = 5;//被操作数
static final int Max = 5;//操作数的最大值
static Boolean order = false;//状态值:false代表递减,true代表递增
private String name;
public zongjie(String name){
// super(name);
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void incre(){
synchronized (this){
while(r >= Max || !order){//当操作数到达最大值或者还是递减状态的情况下
order = false;
System.out.println("太大了,需要递减!");
this.notifyAll();//唤醒其余线程
try{
this.wait();//进入等待
}catch (InterruptedException e){
e.printStackTra