多线程代码有什么问题?

时间:2014-05-11 11:20:00

标签: java multithreading

在我的Server类中,我有以下代码。 为什么执行流程永远不会到达Server类中的while循环?

// 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());
        }
    }
}

在实现Runnable的Source类中,我有:

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...
        }
    }
}

2 个答案:

答案 0 :(得分:1)

问题在于调试方法。在没有客户端连接的情况下使用调试器不会比第一次调用accept()方法更进一步。为了找出问题,您需要在调用System.out.println()之前在Server while循环中放置一个accept()语句,并检查是否输入了循环。

答案 1 :(得分:0)

猜测,但是使用swing需要确保事件处理在正确的线程中完成。

    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);
        }
    }