[英]Thread.join() not working as expected
我正在使用一個線程來重繪一個JPanel(看到repaint()
是線程安全的)。
這是paintComponent方法:
public void paintComponent(Graphics g) {
super.paintComponent(g);
//Print statement so I know where my program is at.
System.out.println("Repainting world...");
g.drawImage(worldImage, x, y, 6144, 4608, null);
}
每當用戶按下某個按鈕時,我都有一個在KeyListener
內部啟動的線程
運行方法:
public void run(){
game.repaint();
}
最后,這是我對使用上述run方法的線程的調用:
//NOTE: I've tried this without the if statement, made no difference
if(!gameThread.isAlive()){
gameThread.start();
try {
gameThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
我很確定,在這種情況下(因為它在KeyListener)
, Thread.join()
停止EDT
直到執行該run方法為止。
問題是,無論我等待多長時間,只要我再次按下該按鈕, Thread.join
都會引發InterruptedException
。 這使我相信線程掛在某個區域的某個地方,線程不會停止其執行。 我只是不知道它可能掛在哪里。
如果我理解這一點...您是在gameThread中調用repaint()。 由於repaint()是在EDT上執行的,因此我認為您是由於gameThread.join()阻止了EDT而阻止了它的執行(因為它是由EDT啟動的,即從您的KeyListener處理程序中)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.