多线程问题,点运行没反应,求指点
[code=javapackage xiancheng;
//定义4个线程 2个执行加法2个执行减法
public class ThreadAddAndJianfa {
public static void main(String[] args) {
Message message= new Message();
Addinfo addinfo =new Addinfo(message);
Subinfo subinfo=new Subinfo(message);
Thread t1= new Thread(addinfo,"加法操作一");
Thread t2= new Thread(addinfo,"加法操作2");
Thread t3= new Thread(subinfo,"减法操作一");
Thread t4= new Thread(subinfo,"减法操作2");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
//定义一个信息 存放加法和减法
class Message{
private int data=10;
private boolean flag=false;
public synchronized void add(){
if(this.flag==false){
try {
super.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("加法操作"+(this.data++));
flag=false;
super.notify();
}
}
//减法
public synchronized void subtract(){
if(this.flag){
try {
super.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("减法操作"+(this.data--));
flag=true;//已经取出来啦
super.notify();
}
}
}
//定义加法生产者
class Addinfo implements Runnable{
private Message message=null;
public Addinfo(Message message) {
this.message = message;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<10;i++){
this.message.add();
}
}
}
//定义减法消费者
class Subinfo implements Runnable{
private Message message=null;
public Subinfo(Message message) {
this.message = message;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<10;i++){
this.message.subtract();;
}
}
}][/code] 求指教,不知道哪里错啦
------解决方案--------------------执行加法操作时,由于flag为false,线程一直处于wait状态,执行减法操作时,由于flag还是false,线程就直接结束了,lz再根据逻辑调试一下吧。