希望有人可以帮我解决这个问题。我有一个多线程服务器应用程序,其中GUI JFrame将不显示组件,直到两个客户端线程都清醒。每个客户端都是使用内部类ext线程创建的线程。
一个客户端通过套接字连接加入,建立了流,然后暂停,直到客户端2加入并且相同。一旦建立了客户端线程并创建了流,客户端1就会被设置为挂起(false),并且两个客户端线程都处于唤醒状态。只是现在JFrame显示组件......
主要方法也在EDT上调用:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
MorseCode_Server serverApp= new MorseCode_Server();
serverApp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
serverApp.execute();
}
不确定这里的代码是什么,所以我添加了以下内容: 这个方法是第一个在外部类中调用的方法,它设置每个客户端/播放器并挂起第一个线程直到第二个准备就绪:
displayMessage("Execute Called(): ");
for (int i = 0; i < players.length; i++) {
try {
players[i] = new Player(socket.accept(), i);//assign soc & playerNumber
//clientIP[i] = //get IP address for message log
players[i].start();//JVM calls the threads run method
displayMessage("Execute(): Player " + players[i] + " socket created in execute (OUTER CLASS)");
//get IP address of playet[i]
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}//end for
//player 0 is suspended once socket created until player 1 is instantiated
//must retrun player 0 to resume state in synchronised block to allow one
//thread access at a time
synchronized (players[0]) {
players[0].setSuspended(false);
players[0].notifyAll();//wake up threads waiting on this object
displayMessage("Execute(): "+ players[0] + " players number notifyAll called in execute");
}//end synchronised block
这是每个客户端线程的内部类构造函数:
private class Player extends Thread {
//instance varibles for each client/player
public Player(Socket accept, int i) {
connection = accept;
//clientIP[i] = connection.getRemoteSocketAddress().toString();
playerNumber = i;
displayMessage("Player " + playerNumber + " costructor thread inner class called");
//open socket streams for communication
try {
//objectouptstream obj wraps the low level code from getOutputStream method
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
displayMessage("Player " + playerNumber + " output/input streams set up in Player inner class..END CONSTRUCTOR PLAYER");
} catch (IOException e) {
e.printStackTrace();
}
}//end constructor inner class Player
此外,当我尝试通过其连接获取clicent的IP地址时:
clientIP[i] = connection.getRemoteSocketAddress().toString();
我得到一个空指针异常!! 提前干杯 ç
答案 0 :(得分:2)
不要在事件调度线程(EDT)上执行长时间运行的代码。这导致GUI冻结。
启动套接字连接的代码应该在单独的线程中执行,因此它不会阻止EDT。有关详细信息,请阅读Concurrency上Swing教程中的部分。您可以创建自己的Thread或使用SwingWorker。