下面的程序效率很低,是不是抛异常很占CPU呢??

liuzheng_jz 2014-03-19 08:03:30
package Scanning;
//import java.io.*;
import java.util.concurrent.CountDownLatch;
/************************************************************
* @author
* 2014-3-11 下午8:45:22
************************************************************/
public class ScannerTest {
public static void main(String[] args) {
PortScanner ps=new PortScanner();
CountDownLatch latch=new CountDownLatch(1);

Thread t1=new Thread(new Scanner1(ps,latch));
//Thread t2=new Thread(new Scanner2(ps,latch));
//Thread t3=new Thread(new Scanner3(ps,latch));
//Thread t4=new Thread(new Scanner4(ps,latch));
// Thread t5=new Thread(new Scanner5(ps,latch));
MainScan ms=new MainScan(latch);
Thread mt=new Thread(ms);

t1.start();
// t2.start();
// t3.start();
// t4.start();
//t5.start();
mt.start();//启动MainScan线程
}

}

package Scanning;
import java.io.*;
//import java.util.*;
import java.net.*;

/************************************************************
* @author
* 2014-3-11 下午7:50:03
* 编写一个程序,

扫描本机的小于5000的端口,显示正在使用的端口号。要求采用5个线程实现,
每个线程扫描1000个端口。
************************************************************/
public class PortScanner {
ServerSocket serversocket=null;
// ArrayList list=new ArrayList();
public void TakeUpPort(int port)
{
try{
serversocket=new ServerSocket(port);//socket绑定端口
serversocket.close();
}catch(IOException e)
{
//list.add(port);
System.err.println(port+" Port already in use");//已占用的端口会抛出异常
}
// System.out.println("Port already in use:"+list);
}


}

package Scanning;
import java.util.concurrent.CountDownLatch;

/************************************************************
* @author
* 2014-3-11 下午9:04:38
************************************************************/
public class Scanner1 implements Runnable {
private PortScanner ps=null;
private CountDownLatch downlatch;
public Scanner1(PortScanner ps,CountDownLatch downlatch)
{
this.ps=ps;
this.downlatch=downlatch;
}
public void run()
{
for(int port=1;port<=65535;port++)
{
ps.TakeUpPort(port);
}
this.downlatch.countDown();
}

}
package Scanning;
import java.io.*;
import java.util.concurrent.CountDownLatch;

/************************************************************
* @author LiuZheng
* 2014-3-14 下午4:54:09
************************************************************/
public class MainScan implements Runnable {
private CountDownLatch downlatch;
public MainScan(CountDownLatch downlatch)
{
this.downlatch=downlatch;
}
public void run()
{
System.out.println("******本机已启用端口******");
try
{
this.downlatch.await();
}catch(InterruptedException e)
{

}
System.out.println("端口扫描完成!按回车退出");
try{
new BufferedReader(new InputStreamReader(System.in)).readLine();
}catch(IOException e)
{
System.out.print(e);
System.exit(0);
}
}

}
...全文
55 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

50,530

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧