从线程请求Threadpool

时间:2013-02-21 17:18:24

标签: java multithreading threadpool

我需要创建一个生成包含以下字符的列表的应用程序:H,A,O,*,#,@。最后两个是控制字符。 "#"使列表分为两部分(如树),每个子列表必须继续填充,直到" @"出现,表示列表已完成。这个过程一直持续到所有的子列表都有" @"或者所有子列表的长度都是10000.

然后我必须使用线程遍历列表,并且每个字符在帧中绘制不同的图像。当我找到"#"时,线程必须启动另外两个线程来迭代接下来的两个子列表,并且必须终止。

当我必须启动新线程并完成第一个线程时,我陷入困境。谷歌搜索我找到了一种方法来做到这一点,但我觉得这是一个不好的方法。所以我的问题是: 还有另一种方法可以做到这一点吗?

public class PainterThread implements Runnable {


public PainterThread(Iterator pIterator, ExecutorService pPool, PaintingPanel pPanel) {
    _iteratorList = pIterator;  //the Iterator of the list
    _Pool = pPool;          //I pass the ThreadPool as a parameter in order to make the request to create new threads
    _PanelToPaint = pPanel;// The Panel which going to paint the images
}

//Methods
@Override
public void run() {
    while (_iteratorList.hasNext()) {
        Node actualNode = (Node) _iteratorList.next();
        switch (actualNode.getControlSign()) {
            case "H":
                _PanelToPaint.addShapes(new Square(actualNode.getPositionX(), actualNode.getPositionY(), actualNode.getSize()));
                _PanelToPaint.repaint();
                break;
            case "A":
                _PanelToPaint.addShapes(new Triangle(actualNode.getPositionX(), actualNode.getPositionY(), actualNode.getSize()));
                _PanelToPaint.repaint();
                break;
            case "O":
                _PanelToPaint.addShapes(new Circle(actualNode.getPositionX(), actualNode.getPositionY(), actualNode.getSize()));
                _PanelToPaint.repaint();
                break;
            case "*":
                _PanelToPaint.addShapes(new Asterisk(actualNode.getPositionX(), actualNode.getPositionY(), actualNode.getSize()));
                _PanelToPaint.repaint();
                break;
            case "#":
                LinkedList actualList = (LinkedList) _iteratorList.next();
                _Pool.submit(new PainterThread(actualList.iterator(), _Pool,_PanelToPaint)); //Here is my question. Is there another way to make this?
                if (_iteratorList.hasNext()) {
                    actualList = (LinkedList) _iteratorList.next();
                    _Pool.submit(new PainterThread(actualList.iterator(), _Pool, _PanelToPaint));
                }
                break;
            case "@":
                break;
        }
    }
}

public void setIterator(Iterator pNewIterator) {
    _iteratorList = pNewIterator;
}
//Atributes
private Iterator _iteratorList;
private ExecutorService _Pool;
private PaintingPanel _PanelToPaint;

}

0 个答案:

没有答案