java应用程序

发布于 2024-11-08 07:36:01 字数 6062 浏览 0 评论 0原文

对于java应用程序:为什么不能在同一个主线程中启动两个不同的线程???

一个线程正在侦听到端口的传入连接,另一个线程侦听到完全不同端口的其他连接???

类似于:

public static void main(String[] args) {

        // TODO Auto-generated method stub


         ClientThread clienThread= new ClientThread();
        new Thread(clienThread).start();

        ThreadPooledServer server = new ThreadPooledServer(6000);
        new Thread(server).start();
    }

其中 ClientThread() 和 ThreadPooledServer() 是两个不同的线程!

问题:为什么java不让我这样做?

public class Start {

    Socket socket;
    private String  serverIpAddress="127.0.0.1";
    static Thread cThread;
    public static void main(String[] args) {
        // TODO Auto-generated method stub


         ClientThread clienThread= new ClientThread();
        new Thread(clienThread).start();

        ThreadPooledServer server = new ThreadPooledServer(6000);
        new Thread(server).start();




    }


}

public class ClientThread implements Runnable {

        public void run() {
            try {
                InetAddress serverAddr = InetAddress.getByName(serverIpAddress);

                socket = new Socket(serverAddr, 6100);

                System.out.println("s-a creat");
            } catch (UnknownHostException e) {
                System.err.println("Don't know about host");
            } catch (IOException e) {
                System.err
                        .println("Couldn't get I/O for the connection to host");
            }


        }
    }

public class ThreadPooledServer implements Runnable {

    protected int serverPort =6000;
    public static String SERVERIP = "127.0.0.1";
    protected ServerSocket serverSocket = null;
    protected boolean isStopped = false;
    protected Thread runningThread = null;
    public static int clientconnection = 0;
    Vector<WorkerRunnable> workerList = null;

     protected ExecutorService threadPool =
            Executors.newFixedThreadPool(5);

    public ThreadPooledServer(int port) {
        this.serverPort = port;
        workerList = new Vector<WorkerRunnable>();
    }

    public void run() {
        synchronized (this) {
            this.runningThread = Thread.currentThread();
        }
        openServerSocket();

        while (!isStopped()) {
            Socket clientSocket = null;
            try {
                System.out.println("Serverul asteapta clienti spre conectare");
                clientSocket = this.serverSocket.accept();
                clientconnection++;
                System.out.println("Serverul a acceptat clientul cu numarul:"
                        + clientconnection);
                // Log.d("Server:","s-a acceptat un nou client");

            } catch (IOException e) {
                if (isStopped()) {
                    System.out.println("Server Stopped.");
                    return;
                }
                throw new RuntimeException("Error accepting client connection",
                        e);
            }
            // creare thread pt noul client conectat
            //WorkerRunnable workerRunnable = new WorkerRunnable(clientSocket);
            //Thread workerThread = this.threadPool.execute(new WorkerRunnable(clientSocket));
            //workerThread.start();
            this.threadPool.execute(new WorkerRunnable(clientSocket));
            //this.workerList.add(workerRunnable);
        }
        this.threadPool.shutdown();
        System.out.println("Server Stopped.");
    }

    private synchronized boolean isStopped() {
        return this.isStopped;
    }

    public synchronized void stop() {
        this.isStopped = true;
        try {
            this.serverSocket.close();
            // stop thread-uri workers
            for (int i = 0; i < this.workerList.size(); i++) {
                WorkerRunnable worker = this.workerList.elementAt(i);
                worker.stop();
            }
        } catch (IOException e) {
            throw new RuntimeException("Error closing server", e);
        }
    }

    private void openServerSocket() {
        try {
            InetSocketAddress serverAddr = new InetSocketAddress(SERVERIP,
                    serverPort);
            serverSocket = new ServerSocket();
            serverSocket.bind(serverAddr);

        } catch (IOException e) {
            throw new RuntimeException("Cannot open port 6000", e);
        }
    }
}

public class WorkerRunnable implements Runnable {

    protected Socket clientSocket = null;
    Scanner s = null;
    String longitude;
    String latitude;

    boolean stop = false;

    public WorkerRunnable(Socket clientSocket) {
        this.clientSocket = clientSocket;

    }

    public void run() {

        try {

            System.out.println("O noua conexiune acceptata"
                    + clientSocket.getInetAddress() + "cu portul"
                    + clientSocket.getPort());

            Scanner is = new Scanner(new DataInputStream(
                    this.clientSocket.getInputStream()));
            while (!stop) {

                while (is.hasNext()) {
                    try {
                        longitude = is.next();
                        latitude = is.next();
        System.out.println(longitude);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            is.close();
            clientSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void stop() {
        this.stop = true;
    }

这就是我的全部了!!!

编辑:我将 ClientThread 代码移至不同的类中,并且成功运行了我的代码,但现在我无法创建两个套接字。

我的意思是它创建了一个,但对于第二个我得到:

“无法获取与主机连接的 I/O”

我认为这是来自这里:

 catch (IOException e) {

                System.err
                        .println("Couldn't get I/O for the 
connection to host");

        }

有人知道为什么吗?

For a java application:Why isn't there possible to start two different threads in the same main???

One thread that is listening form incoming connections to a port and another thread that listens for other connections to a totally different port???

Something like:

public static void main(String[] args) {

        // TODO Auto-generated method stub


         ClientThread clienThread= new ClientThread();
        new Thread(clienThread).start();

        ThreadPooledServer server = new ThreadPooledServer(6000);
        new Thread(server).start();
    }

Where ClientThread() and ThreadPooledServer() are two different threads!

Question:Why doesn't java let me do that?

public class Start {

    Socket socket;
    private String  serverIpAddress="127.0.0.1";
    static Thread cThread;
    public static void main(String[] args) {
        // TODO Auto-generated method stub


         ClientThread clienThread= new ClientThread();
        new Thread(clienThread).start();

        ThreadPooledServer server = new ThreadPooledServer(6000);
        new Thread(server).start();




    }


}

public class ClientThread implements Runnable {

        public void run() {
            try {
                InetAddress serverAddr = InetAddress.getByName(serverIpAddress);

                socket = new Socket(serverAddr, 6100);

                System.out.println("s-a creat");
            } catch (UnknownHostException e) {
                System.err.println("Don't know about host");
            } catch (IOException e) {
                System.err
                        .println("Couldn't get I/O for the connection to host");
            }


        }
    }

public class ThreadPooledServer implements Runnable {

    protected int serverPort =6000;
    public static String SERVERIP = "127.0.0.1";
    protected ServerSocket serverSocket = null;
    protected boolean isStopped = false;
    protected Thread runningThread = null;
    public static int clientconnection = 0;
    Vector<WorkerRunnable> workerList = null;

     protected ExecutorService threadPool =
            Executors.newFixedThreadPool(5);

    public ThreadPooledServer(int port) {
        this.serverPort = port;
        workerList = new Vector<WorkerRunnable>();
    }

    public void run() {
        synchronized (this) {
            this.runningThread = Thread.currentThread();
        }
        openServerSocket();

        while (!isStopped()) {
            Socket clientSocket = null;
            try {
                System.out.println("Serverul asteapta clienti spre conectare");
                clientSocket = this.serverSocket.accept();
                clientconnection++;
                System.out.println("Serverul a acceptat clientul cu numarul:"
                        + clientconnection);
                // Log.d("Server:","s-a acceptat un nou client");

            } catch (IOException e) {
                if (isStopped()) {
                    System.out.println("Server Stopped.");
                    return;
                }
                throw new RuntimeException("Error accepting client connection",
                        e);
            }
            // creare thread pt noul client conectat
            //WorkerRunnable workerRunnable = new WorkerRunnable(clientSocket);
            //Thread workerThread = this.threadPool.execute(new WorkerRunnable(clientSocket));
            //workerThread.start();
            this.threadPool.execute(new WorkerRunnable(clientSocket));
            //this.workerList.add(workerRunnable);
        }
        this.threadPool.shutdown();
        System.out.println("Server Stopped.");
    }

    private synchronized boolean isStopped() {
        return this.isStopped;
    }

    public synchronized void stop() {
        this.isStopped = true;
        try {
            this.serverSocket.close();
            // stop thread-uri workers
            for (int i = 0; i < this.workerList.size(); i++) {
                WorkerRunnable worker = this.workerList.elementAt(i);
                worker.stop();
            }
        } catch (IOException e) {
            throw new RuntimeException("Error closing server", e);
        }
    }

    private void openServerSocket() {
        try {
            InetSocketAddress serverAddr = new InetSocketAddress(SERVERIP,
                    serverPort);
            serverSocket = new ServerSocket();
            serverSocket.bind(serverAddr);

        } catch (IOException e) {
            throw new RuntimeException("Cannot open port 6000", e);
        }
    }
}

public class WorkerRunnable implements Runnable {

    protected Socket clientSocket = null;
    Scanner s = null;
    String longitude;
    String latitude;

    boolean stop = false;

    public WorkerRunnable(Socket clientSocket) {
        this.clientSocket = clientSocket;

    }

    public void run() {

        try {

            System.out.println("O noua conexiune acceptata"
                    + clientSocket.getInetAddress() + "cu portul"
                    + clientSocket.getPort());

            Scanner is = new Scanner(new DataInputStream(
                    this.clientSocket.getInputStream()));
            while (!stop) {

                while (is.hasNext()) {
                    try {
                        longitude = is.next();
                        latitude = is.next();
        System.out.println(longitude);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            is.close();
            clientSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void stop() {
        this.stop = true;
    }

This is all I have!!!

EDIT:I moved the ClientThread code into a different class and I succeded to run my code,but now I can't get to create two sockets.

I mean it creates one but for the second one I get:

"Couldn't get I/O for the connection to host"

I assume that is coming from here:

 catch (IOException e) {

                System.err
                        .println("Couldn't get I/O for the 
connection to host");

        }

Does someone knows why??

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

你另情深 2024-11-15 07:36:01

这与线程或套接字无关。您收到的错误描述为这里。如果没有看到您的代码,我会说您尝试实例化的类是 Start 的内部类。您没有 Start 的实例,因为您处于其静态 main() 方法中。

尝试类似的东西:

public class Start
{
  public static void main(String[] args)
  {
    Start myStart = new Start();
    myStart.doIt();
  }

  private void doIt()
  {
    ClientThread clienThread= new ClientThread();
    new Thread(clienThread).start();

    ThreadPooledServer server = new ThreadPooledServer(6000);
    new Thread(server).start();
  }
}

This has nothing to do with threads or sockets. The error you are getting is described here. Without seeing your code I'd say that the classes you are trying to instantiate are inner classes of Start. You don't have an instance of Start because you're in its static main() method.

try something like:

public class Start
{
  public static void main(String[] args)
  {
    Start myStart = new Start();
    myStart.doIt();
  }

  private void doIt()
  {
    ClientThread clienThread= new ClientThread();
    new Thread(clienThread).start();

    ThreadPooledServer server = new ThreadPooledServer(6000);
    new Thread(server).start();
  }
}
走野 2024-11-15 07:36:01

绝对可以根据需要从 main() 启动任意数量的线程(操作系统可能会施加一些限制)。

不幸的是我的水晶球正在修复,所以我只能猜测可能会出现什么问题:
- 另一个进程绑定到端口 6000(也许是您的 java 程序的旧实例?)
- 线程中的一些同步导致它们死锁
- 其他的东西;-)

也许你可以澄清你的问题?

It's absolutely possible to start as many Threads from main() as you wish (the OS might impose some limit).

Unfortunately my crystal ball is in repair, so I can only guess what might run wrong:
- another process is bound to port 6000 (maybe an old instance of your java program?)
- some synchronization in the Threads deadlocks them
- something else ;-)

Maybe you can clarify you problem?

关于“无法访问 Start 类型的封闭实例。”:

要么在构造函数中创建步骤并创建类的新对象,要么将内部类声明为静态(如果不需要访问外部类成员)

Regarding the "No enclosing instance of type Start is accessible.":

Either create the treads in the constructor and create a new object of your class or declare the inner class static (if it does not need access to outer classes members)

痴骨ら 2024-11-15 07:36:01

根据评论中的反馈 -
“无法访问 Start 类型的封闭实例。必须使用 Start 类型的封闭实例来限定分配(例如 xnew A(),其中 x 是 Start 的实例”
看起来类 Start 恰好是某个类 X 的内部类。初始化内部类的实例并不像“普通类”那么简单。不能使用以下表示法初始化内部类:

Outer.Inner obj = new Outer.Inner();

相反,必须使用以下表示法:

Outer.Inner obj = outerObj.new Inner();

其中 Outer 是封闭类,Inner 是封闭类,而 externalObj 是封闭类的实例。

PS:请在您的问题中包含更多信息,以便任何人都有机会确定问题。您原来的问题不包含任何有助于帮助您的信息。

Based on the feedback in the comment -
"No enclosing instance of type Start is accessible. Must qualify the allocation with an enclosing instance of type Start (e.g. x.new A() where x is an instance of Start"
it appears that the class Start happens to be an inner class of some class X. Initializing an instance of an inner class is not as trivial as for an "ordinary class". One cannot initialize an inner class using the following notation:

Outer.Inner obj = new Outer.Inner();

Instead the following notation must be used:

Outer.Inner obj = outerObj.new Inner();

where Outer is the enclosing class and Inner is the enclosed class, and outerObj is an instance of the enclosing class.

PS: Please include more information in your questions to give anybody a chance at determining the problem. Your original question contains no information whatsoever that will aid in helping you out.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文