ExecutorServiceインタフェースのアプリケーション、スレッドプールの作成

1474 ワード

メインクラス:test.java
 
import java.io.IOException;

public class test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			NetworkService instance = new  NetworkService(100);
			instance.serve();// 
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	 
}

 
 
2.別途作成したスレッドマスター
 
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class NetworkService {
	    private final ExecutorService pool;
	    public NetworkService(int poolSize) throws IOException {
	      pool = Executors.newFixedThreadPool(poolSize);
	    }
	 
	    public void serve() {
	      for (int i =0;;i++) {
		  pool.execute(new Handler(" :",i+1));
		}
	    }
	  }

class Handler implements Runnable {
  private final String taskcontent;
  private final int index;
  Handler(String taskcontent,int index) { 
	  this.index =  index;
	  this.taskcontent = taskcontent; }
  public void run() {
       System.out.println(taskcontent+index);
  }
}

forでタスクをすべてスレッドプールに入れ、最大100個のタスクしか収容できず、実行順序が異なります.