2011-03-06 52 views
1

我想在我的applet中使用4個線程並使用Runnable接口想要將所有線程移動到所需的位置周圍。Java中的多線程

當我在我的小程序中,雲圖像從y軸從o行走到750,直升機開始行走,當y軸處的雲達到150時,直升機行走到達到350,然後此線程停止。 然後,當我的直升機達到200時,一個男人的圖像出來,走到X軸,它走了5到10毫秒時會停止。

下面是我的代碼:

所有的
import java.applet.* ; 

package com.pack; 

import java.applet.*; 
import java.awt.*; 
import java.awt.event.*; 

public class HelicopterScene extends Applet { 
    Image a, b, c; 
    int i, j, h, p; 

    public void init() { 
     i = 20; 
     j = 750; 
     h = 0; 
     a = getImage(getCodeBase(), "HelicopterAttack.jpg"); 
     b = getImage(getCodeBase(), "pppp.png"); 
     c = getImage(getCodeBase(), "helicopter1.png"); 
    } 

    public void paint(Graphics g) { 
     showStatus(" Helicopter Scene Applet is started....."); 
     g.drawImage(a, 0, 0, this); 
     if (i <= 750 && j >= 20) { 
      if (i >= 150) { 
       g.drawImage(c, h, 255, 150, 35, this); 
       h++; 
       repaint(); 
       try { 
        Thread.sleep(20); 
       } catch (InterruptedException w) { 
       } 
      } 

      g.drawImage(b, j, 120, 90, 70, this); 
      g.drawImage(b, i, 180, 120, 70, this); 
      i++; 
      j--; 
      repaint(); 
      try { 
       Thread.sleep(10); 
       if (i == 750 && j == 20) { 
        p = h; 
        g.drawImage(c, p, 255, 150, 35, this); 
        h++; 
        repaint(); 
        try { 
         Thread.sleep(20); 
        } catch (InterruptedException w) { 
        } 
        i = 20; 
        j = 750; 
       } 
      } catch (InterruptedException e) { 
      } 
     } 
    } 
} 
+0

這不行嗎? – 2011-03-06 19:51:11

+0

如果這是一項功課,請爲問題添加適當的標籤。 – Crozin 2011-03-06 20:16:50

回答

1

首先,你永遠要在UI線程上睡覺。其次,你永遠不想畫關閉的UI線程。你應該調查SwingUtilities.invokeLater()。

+0

請問你能告訴我如何? 因爲我新的Java概念,所以我將不勝感激,如果你幫我... 並感謝您的答覆... – user647247 2011-03-08 14:31:28

+1

http://download.oracle.com/javase/6/docs/api/javax/swing /SwingUtilities.html#invokeLater%28java.lang.Runnable%29 – 2011-03-09 04:54:31