题目:设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1
问题:我的程序出来的答案是错的,帮我修改一下,谢谢
代码:
package phrase3;
class tongbu{
private boolean available=false;
synchronized void plus(){
while(available==true)
try{
wait();
}catch(InterruptedException e){}
available=true;
notify();
}
synchronized void minus(){
while(available==false)
try{
wait();
}catch(InterruptedException e){}
available=false;
notify();
}
}
class Plus extends Thread{
private tongbu tb;
int num=0;
public Plus(tongbu thistb){
tb=thistb;
}
public void run(){
for(int i=0;i<100;i++){
num+=1;
System.out.println("the num plus:"+num);
tb.plus();
}
}
}
class Minus extends Thread{
private tongbu tb;
int num=0;
public Minus(tongbu thistb){
tb=thistb;
}
public void run(){
for(int i=0;i<100;i++){
num-=1;
System.out.println("the num minus:"+num);
tb.plus();
}
}
}
//class Minus implements Runnable{
// private tongbu tb;
// int num=0;
// public Minus(tongbu thistb){
// tb=thistb;
// }
// public void run() {
// for(int i=0;i<100;i++){
// num-=1;
// System.out.println("the num minus:"+num);
// tb.plus();
// }
// }
//
//}
public class MyThread {
public static void main(String args[]){
tongbu tb=new tongbu();
Plus p1=new Plus(tb);
Plus p2=new Plus(tb);
Minus m1=new Minus(tb);
Minus m2=new Minus(tb);
Thread t1=new Thread(m1);
Thread t2=new Thread(m2);
p1.start();
p2.start();
t1.start();
t2.start();
}
}