开始的时候 run()方法没有用 synchronized
会出现i>120的情况 121,122
然后采用 synchronized run() 以后
错误是没了
可速度和没采用线程一样慢了!!
请大家帮忙啊
让 速度快,又不会出错啊!!import java.net.*;
import java.io.*;class SocketDemo
{
 public static void main(String args[])
 {
 String host="127.0.0.1";
 if(args.length>0) {host=args[0];}
 
 ScanPort sp=new ScanPort(host);
 new Thread(sp).start();
 new Thread(sp).start();
 new Thread(sp).start(); }
}class ScanPort implements Runnable
{
int i;
String host;
boolean flag=true;
Socket s;

public ScanPort(String host)
{ this.host=host;}

public synchronized void run()  
{
 while(flag)
 {
  try
  {
  s=new Socket(host,i);
  System.out.println("the port:"+i+" is open!");
  }
  catch(UnknownHostException e)
  {
   System.err.println(e);
   break;
  }
  catch(IOException e)
  {System.out.println(i+" not open");}
  finally 
  {
    try
    { if(s!=null) s.close(); }
    catch(IOException e)
    {}
     
  }
  
  i++;
  if(i>120)
  {flag=false;}  }//end while
}//end run
}//end ScanPort