线程池实现 - 我做得对吗?

时间:2015-08-12 13:09:55

标签: java multithreading threadpool

我是多线程的新手。 我很难理解我的实现有什么问题,以及为什么我看到的每个实现都使用synchronized块和notifys。 运行似乎没问题,所以我不能指出究竟什么不好但是我认为有一些多线程原则我不跟随。

这是代码:

public class Threads {
static Queue<MyThread> queue = new LinkedList<>();
static Thread[] threadsArr = new Thread[10];

public static void main(String[] args) throws InterruptedException {
    Threads t = new Threads();
    t.startArr();
    t.startProcess();
}
void startArr(){
    for (int i=0;i<10;i++){
        threadsArr[i] = new Thread(new MyThread(i));
    }
}
void startProcess(){

    for (int i=0;i<100;i++){
        queue.add(new MyThread(i));
    }
    for (int i=0;i<100;i++){
        int insertPlace = 0;
        boolean isFull = true;
        while (isFull){
            for (int j=0;j<10;j++){
                if (!threadsArr[j].isAlive()){
                    insertPlace = j;
                    isFull = false;
                }
            }
        }
        threadsArr[insertPlace] = new Thread(new MyThread(i));
        threadsArr[insertPlace].start();
    }
}

}

和MyThread类:

public class MyThread implements Runnable {
int threadNumber;
public MyThread(int threadNumber){
    this.threadNumber = threadNumber;
}

@Override
public void run() {
    System.out.println(threadNumber + " started.");
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println(threadNumber + " finished.");

}

}

感谢。

1 个答案:

答案 0 :(得分:0)

我认为主要的问题是你错过了一个&#34; ThreadPoolExecutor&#34;的角色。基本上,使用您的类的用户希望能够调用&#34;执行(Runnable run)&#34;方法,知道你的Threads类将处理允许创建的进程中的执行。 您应该重新编写类的API并提供这种方法(例如,参见实际的ThreadPoolExecutor http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html)。

其次,如果你正在接受求职面试的培训,那就试着写一些更干净,更灵活的代码,不要像往常一样#10;&#34;全班同学。这应该是您的类的用户(在构造函数中)提供的属性,指定他想要允许的线程数(再次看到真正的ThreadPoolExecutor)。

最后,我不是实现ThreadPoolExecutors的专家,但您可以考虑使用BlockingQueue(http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html)来支持,引用&#34;等待队列在检索时变为非空的操作元素&#34 ;.这对于等待Thread可用非常有用,而不是自己动手。但我想有更好的答案。

祝你好运,

的Mathias

相关问题