사용자 정의 스 레 드 탱크 (경계 대기 열 있 음)

2272 단어 자바
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class UseExecutors {
	public static void main(String[] args) {
		
		ThreadPoolExecutor pool = new ThreadPoolExecutor(
				1,  // coresize
				2,  // maxsize
				60, 
				TimeUnit.SECONDS,
				new ArrayBlockingQueue(3)
				,new MyRejected()
				);
		MyTask mt1 = new MyTask(1, "  1");
		MyTask mt2 = new MyTask(2, "  2");
		MyTask mt3 = new MyTask(3, "  3");
		MyTask mt4 = new MyTask(4, "  4");
		MyTask mt5 = new MyTask(5, "  5");
		MyTask mt6 = new MyTask(6, "  6");
		MyTask mt7 = new MyTask(7, "  7");
		
		pool.execute(mt1);
		pool.execute(mt2);
		pool.execute(mt3);
		pool.execute(mt4);
		pool.execute(mt5);
		pool.execute(mt6);
		pool.execute(mt7);
		
		pool.shutdown();
	}
}
public class MyTask implements Runnable{

	private int taskId;
	private String taskName;
	
	public int getTaskId() {
		return taskId;
	}

	public void setTaskId(int taskId) {
		this.taskId = taskId;
	}

	public String getTaskName() {
		return taskName;
	}

	public void setTaskName(String taskName) {
		this.taskName = taskName;
	}

	public MyTask(int taskId, String taskName) {
		super();
		this.taskId = taskId;
		this.taskName = taskName;
	}

	public String toString() {
		return Integer.toString(this.taskId);
	}
	
	@Override
	public void run() {
		try {
			System.out.println("run taskId = " + this.taskId);
			Thread.sleep(5*1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

public class MyRejected implements RejectedExecutionHandler {
	
	@Override
	public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
		// TODO Auto-generated method stub
		System.out.println("     ...");
		System.out.println("        :"+ r.toString());
	}
}
      :

run taskId = 1
run taskId = 5
     ...
        :6
     ...
        :7
run taskId = 2
run taskId = 3
run taskId = 4

좋은 웹페이지 즐겨찾기