【发布时间】:2015-11-05 02:58:23
【问题描述】:
我是多线程的新手。 我很难理解我的实现有什么问题,以及为什么我看到的每个实现都使用同步块和通知。 运行似乎没问题,所以我不能指出到底是什么不好,但我认为有一些我没有遵循的多线程原则。
这是代码:
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.");
}
}
谢谢。
【问题讨论】:
-
你为什么要写自己的线程池? Java 已经有
ThreadPoolExecutor -
如果你不是很懂线程,写一个线程池是个坏主意。
-
我在一次工作面试中得到了这个任务。所以我试图为下一次面试改进。我也在尝试了解多线程的基础知识。
-
代码中的主要问题是它不是线程池。作为客户端,我如何利用池中的线程并在不再需要时将其返回给它?
标签: java multithreading threadpool