我正在尝试在另一个类中调用一个方法,但是,我收到了一个错误。我将类初始化为变量,但我没有选择调用该方法。当我开始输入时,甚至连变量都不会显示在自动完成中。
这是我正在打电话的课程:
public class aMessageBuffer {
private Collection<Message> messageBuffer = new ArrayList<Message>();
private Collection<Integer> responseBuffer = new ArrayList<Integer>();
private boolean messageBufferFull = false;
private boolean responseBufferFull = false;
//Called by aProducerTask
public void sendMsg(String op, int val){
//place message in messageBuffer
Message msg = new Message();
msg.setValues(op,val);
messageBuffer.add(msg);
messageBufferFull = true;
//todo: notify
while (responseBufferFull == false){
//wait...
}
//remove response from responseBuffer
responseBuffer.clear();
responseBufferFull = false;
//todo: Out Response
}
}
这就是我从以下地方打电话的地方:
public class aProducerTask extends Thread {
//TODO: Send Messages
private aMessageBuffer msgbuf = new aMessageBuffer();
msgbuf.sendMsg("add",3);
//TODO: Print Results
}
我在msgbuf.sendMsg("add",3);
收到错误
它不允许我用该变量调用方法
这是我的主要:
public class Main{
public static void main(String args[]){
new aConsumerTask().start();
new aProducerTask().start();
}
public void run() {
}
}
答案 0 :(得分:2)
您应该在类aProducerTask中定义run方法。
public class aProducerTask extends Thread {
//TODO: Send Messages
private aMessageBuffer msgbuf = new aMessageBuffer();
public void run() {
msgbuf.send("add",3);
}
//TODO: Print Results
}
答案 1 :(得分:1)
run
方法中调用非分配方法。run
方法来保存你的方法调用。然后在需要时创建一个新线程,传入Runnable并在线程上调用start()
。所以不是:
public class aProducerTask extends Thread {
//TODO: Send Messages
private aMessageBuffer msgbuf = new aMessageBuffer();
msgbuf.sendMsg("add",3);
//TODO: Print Results
}
而是这个:
// improve class name and have it implement Runnable
public class AProducerTask implements Runnable {
private aMessageBuffer msgbuf = new aMessageBuffer();
@Override // don't forget this!
public void run() {
msgbuf.sendMsg("add",3);
}
}
然后使用:
public new Thread(new AProducerTask()).start();