死线程

时间:2015-04-21 09:19:58

标签: java multithreading

我想制作一个Die gui,每当显示不同的数字时,它会改变模具的表面。我有一个RollDie类扩展了gui类Die:

public class RollDie2 extends Die implements Runnable {

public static void main(String[] args) {

    long sleeptime = 500;
    int times;
    Random rd = new Random();
    int face;
    int facebefore;

    times = rd.nextInt(20)+1;
    face = rd.nextInt(6) + 1;

    // Graphics
    SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            Die die = new RollDie2();

            die.setVisible(true);
          }
        });



    for (int i=0; i<times; i++) {
        (new Thread(new RollDie2(face))).start();
        try {
            Thread.sleep(sleeptime);
        } catch (InterruptedException e) {e.printStackTrace();}
        sleeptime += 100;

        facebefore = face;
        face = rd.nextInt(6) + 1;

        while (facebefore == face) //so it is different every time
            face = rd.nextInt(6) + 1;
    }
    System.out.println("The die was rolled " + times + " times.");



}

int face;

public RollDie2(int face) {
    this.face = face;
    super.changeFace(face);

}
public RollDie2() {

}
@Override
public void run() {

    System.out.println("The face is now showing: " + face);
}

}

GUI类:

public class Die extends JFrame {
int face;

public Die() {
    init();

}


private void init() {
    //final 
    DiePanel surface = new DiePanel();
    add(surface);
   // surface.updateVal(face);
    addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            Timer timer = surface.getTimer();
            timer.stop();
        }
    });

    setTitle("Dice");
    setSize(500, 300);
    //setLocationRelativeTo(null);
    setLayout(new GridLayout(1,3));
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void changeFace(int value) {
    face = value;

}
public int getFace() {
    return face;
}
}

问题是我每次在面板类中调用 getFace()时都不返回任何内容,我无法更新Die的值。我认为这与线程有关,但不知道是什么。

1 个答案:

答案 0 :(得分:0)

我看到你错过了一套方法。 你的代码也到处都是。线程很棘手。下面的代码帮助我一次运行多个线程。它可能有助于你的线程问题。

public class RollDie implements Runnable
{
//variables go here

public RollDie()
{
  start();
}

public void start()
{
 Thread thread = new thread(this);
 thread.start();
}

public void run()
{
//code for RollDie goes here
}

} 

然后从你的骰子类中调用你的RollDie构造函数。 希望这会有所帮助。