线程池+队列 优先级方式执行队列任务

package com;

import java.util.concurrent.TimeUnit;

public class MyPriorityTask implements Runnable, Comparable {

	private int priority;
	private String name;

	public MyPriorityTask(String name, int priority) {
		this.name = name;
		this.priority = priority;
	}

	public void run() {
		System.out.printf("MyPriorityTask: %s Priority :%d\n", name, priority);
		try {
			TimeUnit.SECONDS.sleep(2);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

	public int compareTo(MyPriorityTask o) {
		if (this.getPriority() < o.getPriority()) {
			return 1;
		}
		if (this.getPriority() > o.getPriority()) {
			return -1;
		}
		return 0;

	}

	public int getPriority() {
		return priority;
	}

}
package com;

import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Main {
	public static void main(String[] args) {
		ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 2, 1, TimeUnit.SECONDS, new PriorityBlockingQueue());

		for (int i = 0; i < 100; i++) {
			MyPriorityTask task = new MyPriorityTask("Task " + i, 0);
			executor.execute(task);
			System.out.println(executor.getTaskCount());
		}
		
		
		try {
			TimeUnit.SECONDS.sleep(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		for (int i = 101; i < 8; i++) {
			MyPriorityTask task = new MyPriorityTask("Task " + i, 1);
			executor.execute(task);
			System.out.println(executor.getTaskCount());
		}
		
			

		try {
			 executor.awaitTermination(1, TimeUnit.DAYS);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		System.out.printf("Main: End of the program.\n");

	}
}

 
  


你可能感兴趣的:(java技术)