Java本身支持多线程,要理解并运用好Java多线程机制并不是一件容易的事。在Java多线程中线程的同步是一个重点。
进水排水问题是一个非常简单的Java多线程同步的运用。假设有一个水池,池中有进水与排水两个孔,每次只能单独进水或排水,且进水或排水量为1立方米,现池中有10立方米的水,水池满时不能进水,只能排水,水池空时只能进水不能排水。用两个线程来模拟进水与排水,WaterPool类作为资源类,其中使用了同步方法dewatering(排水)和bilging(进水),当水池满时,进水线程阻塞,并通知排水线程开始排水,当排完水时,应阻塞排水线程同时唤醒进水进程。
分析:如果是80/5 要挑水16次。 如果水缸是81L的话,是81/5,要挑16.2次, 不符合逻辑,不可能挑0.2次水的情况,所以最后的1L升水,还得挑一次水。16+1=17次。
java里 int /int结果还是int 。所以定义变量时使用double比较好。
public class Test。
public static void main(String[] args) 。
double sg = 80。
double st = 5。
int num = (int)(Math.ceil(sg/st))//天花板取整 假如水缸是81L,81/5= 16.2,Math.ceil(16.2)==>得到17.0 然后使用(int)强制把17.0转成整型17。
System.out.println(num)。
public class WaterRate {int type
int quantity
public WaterRate(int type, int quantity) {
super()
this.type = type
this.quantity = quantity
}
public double calc(){
double cash=0
if(type==1){
if(quantity>10){
cash = 10*2.5+(quantity-10)*3
}else{
cash = quantity*2.5
}
System.out.print("生活用水"+quantity+"吨,总计:")
}else if(type==2){
if(quantity>20){
cash = 10*3.9+(quantity-10)*4.8
}else{
cash = quantity*3.9
}
System.out.print("商业用水"+quantity+"吨,总计:")
}else{
System.out.println("请输入正确的类型(1生活用水2商业永硕)")
}
System.out.println(cash+"元")
return cash
}
public static void main(String[] args) {
new WaterRate(1, 16).calc()
new WaterRate(2, 35).calc()
}
}之前就回答你了╮(╯_╰)╭