package cputest;

import java.net.*;
import java.io.*;

public class HttpTest extends Thread{
  private boolean stop=false;
  private String name="Thread-";
  private java.io.PrintStream out=null;
  private java.io.Writer writer=null;
  private String page="";


  public HttpTest(int i,String page,java.io.PrintStream out) {
    this.name=this.name+i;
    this.out=out;
    this.page=page;
  }

  public HttpTest(int i,String page,java.io.Writer writer) {
    this.name=this.name+i;
    this.writer=writer;
    this.page=page;
  }

  public void run() {
    int i=1;
    while(!stop) {
      i++;
      try {
        BufferedReader reader=new BufferedReader(new InputStreamReader(new URL(page).openStream()));
        String line;
        do{
          line=reader.readLine();
        }while(line!=null);
        reader.close();
        reader=null;
      }catch(Exception err) {
        err.printStackTrace();
      }
      if (i%1000==0) {
        if (out!=null)
          out.println(this.name + "--> " + i + " pages readed");
        else
          try {
            writer.write(this.name + "--> " + i + " pages readed\n");
          }catch(Exception err){}
      }
    }
    System.out.println(this.name+"--> "+i+ "pages readed");
  }

  public void stopThread(){
    this.stop=true;
  }

  public static void main(String [] args) {
    int cores=Integer.parseInt(args[0]);
    int time=Integer.parseInt(args[1]);
    String page=args[2];
    java.util.Vector v=new java.util.Vector();
    System.out.println("***********START*******************");
    for(int i=1;i<=cores;i++) {
      HttpTest t=new HttpTest(i,page,System.out);
      t.start();
      v.addElement(t);
    }
    try {
      Thread.sleep(time * 1000);
    }catch(Exception err) {}
    for(int i=0;i<v.size();i++) {
      HttpTest t=(HttpTest)v.elementAt(i);
      t.stopThread();
    }
    System.out.println("************STOP*******************");
  }
}
