Filedialog is killing my thread

你离开我真会死。 提交于 2019-12-25 16:51:45

问题


Im working on a socket program in Java. Im running a GUI with a socket server in the background. The socket server is running a thread that checks for socket messages every 10ms. Both of them runs fine together but as soon as I try to open my File dialog in the gui, the gui crashes, but the server keeps on running. Im thinking that I run the server (or the server thread) in a wrong way. The file dialog works fine if I skip the socket.

What could be the problem, could it be that Im running the thread in a wrong way?

(this in one class)

public ServerController(){
        ServSocket st = new ServSocket();
    Thread thread1=new Thread(st);
    thread1.start();
    }

(this is my thread)

public void run(){
    while (true) {
        try { 
            Thread.sleep(10);
        }
        catch (InterruptedException e) {}

        switch (Status) {
        case CONNECTED:
            try {

                socket = new Socket(hostIP, port);
                System.out.println("Connected on: " + hostIP + port);

                out = new PrintWriter(socket.getOutputStream(), true);
                changeStatus(STARTSENDING, true);
            }
            catch (IOException e) {
                System.out.println("disconnected");
            }
            break;

(and this is my main)

 static ServerController scon;
 static Controller cn;

 public static void main(String[] args) {
     scon = new ServerController();
      cn = new Controller();
     cn.gui();


      }

回答1:


Just guessing here, but I think it's relating to the EDT.

Are you trying to launch the dialog from outside the EDT? http://en.wikipedia.org/wiki/Event_dispatching_thread

If you think you might be, try using SwingUtilities static methods (specifically isEventDispatchThread and invokeLater) to hone in and rectify the issue:

http://java.sun.com/javase/6/docs/api/javax/swing/SwingUtilities.html#isEventDispatchThread()

http://java.sun.com/javase/6/docs/api/javax/swing/SwingUtilities.html#invokeLater(java.lang.Runnable)

hth




回答2:


The problem is now solved. Seems that the problem was that i had a scanner that was waiting for input(string = sc.next();) every 10ms in the thread, and after a few input my GUI showed. I removed the Scanner and i now have a working application.



来源:https://stackoverflow.com/questions/4366602/filedialog-is-killing-my-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!