Java如何在几秒钟的线程启动后通知主类

时间:2017-10-24 09:37:45

标签: java multithreading sockets

在主类我开始一个线程并且在线程启动5秒后我想以某种方式向主类发送通知以继续进行其他一些过程。 对于前者我在一个线程中打开套接字连接,一旦打开端口,我希望主类继续执行其他步骤,其中套接字线程侦听传入的请求。

public class SocketPort {
    private int socketPortUsed;

    public int getSocketPortUsed() {
        return socketPortUsed;
    }

    public void setSocketPortUsed(int socketPortUsed) {
        this.socketPortUsed = socketPortUsed;
    }
}

public class SocketTest {
    public static void main(String[] args) throws InterruptedException {
        SocketPort socketPort = new SocketPort();
        SocketThread thread1 = new SocketThread(socketPort);
        Thread t1 = new Thread(thread1, "thread1");
        t1.start();

        synchronized (socketPort) {
            socketPort.wait();
            System.out.println("socket port opened " + socketPort.getSocketPortUsed());
        }
        // some other steps once port is opened .....

        System.out.println("== Done ==");
    }
}

public class SocketThread implements Runnable {

    private SocketPort port;

    public SocketThread(SocketPort p) {
        this.port = p;
    }

    @Override
    public void run() {
        ServerSocket ss = null;
        String name = Thread.currentThread().getName();
        synchronized (port) {
            System.out.println(name + " waiting to get notified at time:" + System.currentTimeMillis());
            try {
                ss = new ServerSocket(0);
                port.setSocketPortUsed(ss.getLocalPort());
                port.notify();

                System.out.println(name + " waiter thread got notified at time:" + System.currentTimeMillis());
                System.out.println("Socket port opened : " + port.getSocketPortUsed());

                Thread.sleep(10000);
                System.out.println("closing socket connection");
                ss.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}

0 个答案:

没有答案