优先级PriorityBlockingQueue线程队列执行顺序

package com.derbysoft.common.thread;

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

public class ThreadTest {

    public static void main(String[] args) throws InterruptedException {
        Runnable r1 = () -> System.out.println("Hello, World");

        Runnable r2 = () -> System.out.println("Hello, China");
        ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 1, TimeUnit.MINUTES, new PriorityBlockingQueue<>(5), new ThreadPoolExecutor.DiscardOldestPolicy());

        /*executor.getQueue().offer(r2);
        executor.getQueue().offer(r2);
        executor.getQueue().offer(r2);
        executor.getQueue().offer(r2);
        executor.getQueue().offer(r2);
        executor.getQueue().offer(r2);*/
        ShopTaskRunnable s1 = new ShopTaskRunnable(1);
        ShopTaskRunnable s2 = new ShopTaskRunnable(2);
        ShopTaskRunnable s3 = new ShopTaskRunnable(3);
        ShopTaskRunnable s4 = new ShopTaskRunnable(4);
        ShopTaskRunnable s5 = new ShopTaskRunnable(5);

        executor.getQueue().offer(s1);
        executor.getQueue().offer(s2);
        executor.getQueue().offer(s3);
        executor.getQueue().offer(s4);
        executor.getQueue().offer(s5);

        System.out.println(executor.getQueue().size());

        //executor.execute(r1);
        executor.execute(() -> {
        });

        Thread.sleep(TimeUnit.SECONDS.toMillis(5));

        System.out.println(executor.getQueue().size());


    }
}
package com.derbysoft.common.thread;

public class ShopTaskRunnable implements Runnable, Comparable {
    private int i;

    public ShopTaskRunnable(int i) {
        this.i = i;
    }

    @Override
    public int compareTo(Object o) {
        return 1;
    }

    @Override
    public void run() {
        System.out.println("Hello, ShopTask " + i);
    }

}

执行结果
5
Hello, ShopTask 1
Hello, ShopTask 3
Hello, ShopTask 5
Hello, ShopTask 2
Hello, ShopTask 4
0

package com.derbysoft.common.thread;

public class ShopTaskRunnable implements Runnable, Comparable {
    private int i;

    public ShopTaskRunnable(int i) {
        this.i = i;
    }

    @Override
    public int compareTo(Object o) {
        if (!o.getClass().equals(ShopTaskRunnable.class)) {
            return 0;
        }

        ShopTaskRunnable o1 = (ShopTaskRunnable) o;
        return Integer.compare(i, o1.i);
    }

    @Override
    public void run() {
        System.out.println("Hello, ShopTask " + i);
    }

}

执行结果
5
Hello, ShopTask 1
Hello, ShopTask 2
Hello, ShopTask 3
Hello, ShopTask 4
Hello, ShopTask 5
0

你可能感兴趣的:(java)