线程的状态异常是什么原因啊?
大家好!我在用郭克华的J2ME聊天系统中,客户端在连接网络时,出现这样的
提示,是什么问题呢?
Uncaught exception java/lang/IllegalThreadStateException.
以下是客户端的代码:
package chatsystem;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import
java.io.IOException;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.ServerSocketConnection;
import javax.microedition.io.SocketConnection;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class ClientChatMidlet extends MIDlet implements CommandListener {
private SocketConnection sc;
private Form form;
private Display display;
private Command cmdSend;
private Command cmdLogin;
private TextField txtName;
private TextField txtMsg;
private DataOutputStream dos;
private DataInputStream dis;
public ClientChatMidlet() {
form = new Form("客户端聊天界面");
cmdSend = new Command("发送消息", Command.SCREEN, 1);
cmdLogin = new Command("登录到 服务器 ", Command.SCREEN, 1);
txtName = new TextField("昵称", "", 10, TextField.ANY);
txtMsg = new TextField("发送信息", "", 255, TextField.ANY);
form.addCommand(cmdLogin);
form.append(txtName);
//form.append(txtMsg);
form.setCommandListener(this);
}
protected void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
display.setCurrent(form);
try {
sc = (SocketConnection) Connector
.open("socket://localhost:999");
System.out.println(sc.getAddress());//显示:127.0.0.1
dis = sc.openDataInputStream();
dos = sc.openDataOutputStream();
//new ChatThread().start();
// System.out.println("new ChatThread().start()没问题吧");
} catch (
IOException e) {
e.printStackTrace();
}
}
public void commandAction(Command c, Displayable d) {
if (c == cmdSend) {
try {
dos.writeUTF(txtMsg.getString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (c == cmdLogin) {
try {
form.removeCommand(cmdLogin);
form.addCommand(cmdSend);
dos.writeUTF(txtName.getString());
// 登录成功,显示发送的信息
form.append(txtMsg);
new ChatThread().start();
// dis = sc.openDataInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
protected void pauseApp() {
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
}
class ChatThread extends Thread {
public ChatThread() {
}
public void run() {
while (true) {
try {
sc = (SocketConnection) Connector
.open("socket://localhost:999");
dis = sc.openDataInputStream();
dos = sc.openDataOutputStream();
dos.writeUTF(txtName.getString());
//运行到这里出错了,下面就不执行了。可能是这里的问题,但不知道如何修改
this.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
------解决方案--------------------