Java thread is in doubt
I previously published a query about Java threads ( link text)
Based on the answers I received, I decided to implement them So I did this on a machine with two CPU cores The code is as follows
import java.net.*; import java.io.*; public class thready implements Runnable{ private Socket num; public thready(Socket a) { this.num=a; } public void run() { try { BufferedInputStream is = new BufferedInputStream(num.getInputStream()); System.out.println("Connected to port"+num); } catch (IOException ex) { //Logger.getLogger(thready.class.getName()).log(Level.SEVERE,null,ex); } } public static void main(String [] args) { int port = 80; int port1= 81; //int count = 0; try{ ServerSocket socket1 = new ServerSocket(port); ServerSocket socket2 = new ServerSocket(port1); while (true) { Socket connection = socket1.accept(); Socket connection1 = socket2.accept(); Runnable runnable =new thready(connection); Runnable run= new thready(connection1); Thread t1=new Thread(runnable); Thread t2=new Thread(run); t1.start(); t2.start(); } } catch(Exception e) { } }}
Now I use HyperTerminal to test this code and connect to port 890 and port 81 (I am using two HyperTerminal instances). As far as I know, the expected behavior should be "connect to port 'port number'" which will be printed once connected to any port (80 or 81) But the output I get from this code is that if I connect to only one port, the required output will not be printed. If I connect to two ports, one by one, the output will only be printed after two ports Therefore, this again caused my initial confusion, that is, whether the two threads execute at the same time or alternately between the two threads
Any suggestion will be of great help
Cheers!
Solution
You called accept. before you started the thread. Acceptance will block until a connection is established, which is why you see what you do If you want to listen to multiple ports, you need [1] to create a thread for each ServerSocket, and then start a communication thread when accept returns, or process the connections one by one in the thread performing listening
[1] This only applies if you use ServerSocket directly. You should probably use it when learning java. NiO package and its sub packages contain classes for multiplexing non blocking I / O, which can be used to listen to multiple sockets in the same thread, for example