【发布时间】:2017-11-01 17:24:32
【问题描述】:
我正在尝试创建两个线程,其中一个使用 keylistener 和 pipedoutputstream 为另一个线程(pipedinputstream)提供输入。我实现它的方式:Main 中的两个 Runnable 类,其中 main(String[] args) 使用 ExecutorService 来控制这两个线程。由于对如何使用其中一些类知之甚少,我几乎没有提出以下内容(跳过一些代码):
public class Main {
final static PipedOutputStream pipedOut = new PipedOutputStream();
final static PipedInputStream pipedIn = new PipedInputStream();
class ListenerOutput extends JPanel implements KeyListener, Runnable {
int eventKey;
char c;
ListenerOutput() {
this.setPreferredSize(new Dimension(500, 500));
addKeyListener(this);
JFrame f = new JFrame();
f.getContentPane().add(new ListenerOutput());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
@Override
{...}
}
class GameLoop implements Runnable {...}
main(String[] args){
try {
pipedOut.connect(pipedIn);
} catch (IOException e) {
e.printStackTrace();
}
ExecutorService service = Executors.newFixedThreadPool(2);
service.execute(new Main().new ListenerOutput());
service.execute(new Main().new GameLoop());
}
问题出在f.getContentPane().add(new ListenerOutput());线上。它是递归的,没有尽头。我知道它会抛出 StackOverflow 错误。但是,我仍然很困惑该怎么做。提前致谢!
【问题讨论】:
-
f.getContentPane().add(this);
标签: java multithreading swing