日期:2014-05-20  浏览次数:20658 次

一道经典的线程面试题
最多能同时运行5个线程,第6个线程只能等待前边的线程执行后才能运行;且后面的线程按优先顺序排队运行。
请写出设计思路及代码

------解决方案--------------------
我觉得第一先判断有多少线程,然后小于5个线程直接一起运行,如果大于5个,就使用for循环将那5个放进循环里,然后每个线程的任务结束时,你可以设计个字段表示有空闲了,然后缺几个就按剩下线程的优先级放进去就好了,希望对你有帮助
------解决方案--------------------
用executorService线程池,加上设置优先权
------解决方案--------------------
我该是有多蛋疼啊,大半夜的:

Java code

package com.ticmy.concurrency;

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

public class TestPriorityTask {
    private static PriorityBlockingQueue<Runnable> workQueue = new PriorityBlockingQueue<Runnable>();
    private static ThreadPoolExecutor pool = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS, workQueue);
    public static void main(String[] args) throws Exception {
        for(int i=0; i<20; i++) {
            pool.execute(new Task(i));
        }
        pool.awaitTermination(0, TimeUnit.MILLISECONDS);
        pool.shutdown();
    }
}



class Task implements Runnable,Comparable<Task> {
    private int priority;//数值越大,优先级越大
    public Task(int priority) {
        this.priority = priority;
    }
    public void run() {
        System.out.println("当前任务优先级:" + priority + ",执行线程:" + Thread.currentThread() + ",执行此句的时间:" + new Date());
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (Exception e){}
    }
    public int compareTo(Task o) {
        return o.priority - priority;
    }
}