我試圖在兩個三角形點擊兩次時激活一個三角形。只要我點擊它們兩次,三角形0開始移動,直到moveX達到20,while(moveX < 20),但它似乎並沒有達到終止狀態,它不會進入:if(t.getState() == Thread.State.TERMINATED),有什麼想法?Java線程並未終止
public class secondFrame extends JFrame implements Runnable {
}
public secondFrame(ChallengesDialog dialog) {
component = new secFrameDrawComponent();
createComponent();
Thread t = new Thread(this);
t.start();
}
private void createComponent() {
sGen = new shapeGenerator(434, 231);
createT();
}
class AddComponentListener implements MouseListener {
public void mouseClicked(MouseEvent event) {
for(int i = 0; i < count; i++) {
if (component.getTri(i).contains(event.getX(), event.getY())) {
component.setShapeFill("triangle", i);
component.repaint();
countColors(i);
setChallenge();
}
...
MouseListener listener = new AddComponentListener();
component.addMouseListener(listener);
public void setChallenge() {
//two red triangles
if(challenge == 1 && triColorCount[1] == 2) {
Thread t = new Thread(component);
t.start();
System.out.println("Thread's state: " + t.getState());
if(t.getState() == Thread.State.TERMINATED) {
//Unreachable
System.out.println("Thread completed");
}
}
}
...
public void run() {
while(threadFlag) {
..
timeLabel.setText("Elapsed time: " + elapsedTime);
..
}
}
public class secFrameDrawComponent extends JComponent implements Runnable {
public void modTriangle(int x, int y) {
sGen.setTriangleOffset(x, y);
triangle[0] = sGen.getTriangle();
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
draw(g2);
}
public void run() {
while(moveX < 20) {
moveX+= 1;
modTriangle(moveX, 0);
repaint();
try {
Thread.sleep(170);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("moveX = " + moveX);
}
System.out.println("Thread completed exec");
}
public void draw(Graphics2D g2) {
g2.setStroke(new BasicStroke(2));
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
modTriangle(moveX, 0);
g2.draw(triangle[0]);
g2.draw(triangle[1]);
}
線程運行需要多長時間?在檢查線程終止之前等待多久? –
最有可能當您檢查另一個線程中的終止時,您的任務甚至沒有安排。在獲得狀態之前添加一些睡眠,看看會發生什麼。 – zeller
我認爲zeller的評論是正確的。 – kosa