Java - 线程优先级(例如来自Thinking in Java)

时间:2017-10-11 22:32:03

标签: java multithreading concurrency

我现在阅读有关Java中Thinking的并发性的章节,我尝试在计算机中重现本书中的示例,并得到了截然不同的结果。

我从子章节优先事项:

public class SimplePriorities implements Runnable {

    private int countDown = 5;
    private volatile double d;
    private int priority;

    public SimplePriorities(int priority) {
        this.priority = priority;
    }

    @Override
    public String toString() {
        return Thread.currentThread() + ": " + countDown;
    }

    @Override
    public void run() {
        Thread.currentThread().setPriority(priority);
        while (true) {
            for (int i = 1; i < 100000; i++) {
                d += (Math.PI + Math.E) / (double) i;
                if (i % 1000 == 0) {
                    Thread.yield();
                }
                System.out.println(this);
                if (--countDown == 0) return;
            }
        }
    }

    public static void main(String[] args) {
        final ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++) {
            executorService.execute(new SimplePriorities(Thread.MIN_PRIORITY));
        }
        executorService.execute(new SimplePriorities(Thread.MAX_PRIORITY));
        executorService.shutdown();
    }
}

结果我得到了:

Thread[pool-1-thread-1,1,main]: 5
Thread[pool-1-thread-4,1,main]: 5
Thread[pool-1-thread-4,1,main]: 4
Thread[pool-1-thread-4,1,main]: 3
Thread[pool-1-thread-4,1,main]: 2
Thread[pool-1-thread-4,1,main]: 1
Thread[pool-1-thread-6,10,main]: 5
Thread[pool-1-thread-6,10,main]: 4
Thread[pool-1-thread-6,10,main]: 3
Thread[pool-1-thread-6,10,main]: 2
Thread[pool-1-thread-6,10,main]: 1
Thread[pool-1-thread-3,1,main]: 5
Thread[pool-1-thread-5,1,main]: 5
Thread[pool-1-thread-2,1,main]: 5
Thread[pool-1-thread-1,1,main]: 4
Thread[pool-1-thread-2,1,main]: 4
Thread[pool-1-thread-5,1,main]: 4
Thread[pool-1-thread-3,1,main]: 4
Thread[pool-1-thread-5,1,main]: 3
Thread[pool-1-thread-2,1,main]: 3
Thread[pool-1-thread-1,1,main]: 3
Thread[pool-1-thread-2,1,main]: 2
Thread[pool-1-thread-5,1,main]: 2
Thread[pool-1-thread-3,1,main]: 3
Thread[pool-1-thread-5,1,main]: 1
Thread[pool-1-thread-2,1,main]: 1
Thread[pool-1-thread-1,1,main]: 2
Thread[pool-1-thread-3,1,main]: 2
Thread[pool-1-thread-1,1,main]: 1
Thread[pool-1-thread-3,1,main]: 1

作者写道,最后一个结果具有最高优先级,但是当我在我的系统中运行此代码时,我获得了不同的优先级,平均而言往往低优先级而不是高优先级,如上所述。

我使用Ubuntu 16.04。

0 个答案:

没有答案