简体   繁体   中英

What's wrong with the multi-threaded code?

In my Server class, I have the following code. Why the execution flow never reaches the while loop in the Server class?

// Server
public class Server {
    public void start(String remote, int rport) {
        try {
            new Thread(new Source(this)).start();

            ServerSocket listenSocket = new ServerSocket(port);
            while (true) {
                Socket clientSocket = listenSocket.accept();
                ServerConnection connection = new ServerConnection(clientSocket, this);
                System.out.println("sdssssaafffffaddfasfd");
                new Thread(connection).start();
            }
        } catch (IOException e) {
            System.out.println("Listen socket:" + e.getMessage());
        }
    }
}

In the Source class which implements Runnable I have:

public class Source implements Runnable {
    private final Server server;

    public Source(Server server) {
        this.server = server;
    }

    @Override
    public void run() {
        Viewer myViewer = new Viewer();
        JFrame frame = new JFrame("Simple Stream Viewer");
        frame.setSize(320, 240);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(myViewer);

        OpenIMAJGrabber grabber = new OpenIMAJGrabber();
        Device device = null;
        Pointer<DeviceList> devices = grabber.getVideoDevices();
        for (Device d : devices.get().asArrayList()) {
            device = d;
            break;
        }

        boolean started = grabber.startSession(320, 240, 30, Pointer.pointerTo(device));
        if (!started) {
            throw new RuntimeException("Not able to start native grabber!");
        }

        while (true) {
            // code runs infinitely here...
        }
    }
}

Th problem is with the debugging method here. Using the debugger without the client connection will not proceed further than the first call to the accept() method. In order find out the problem, you need to put one System.out.println() statement inside the Server while -loop before the call to accept() and check if the loop is entered.

A guess, but with swing one needs to ensure that event handling is done in the correct thread.

    final JFrame frame = new JFrame("Simple Stream Viewer");
    frame.setSize(320, 240);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(myViewer);
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
           frame.setVisible(true);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM