run()方法没有运行

时间:2014-04-27 07:40:18

标签: java multithreading

我想制作一个简单的太空射击游戏,但它在开始时效果不佳。它将如何结束?我的代码出了点问题。 Runnable接口的重写run()方法无效。为什么run方法不能正常工作?此外,任何有关如何射击更多独立子弹的信息。这是我的代码。提前谢谢。

import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;

public class GameWindow extends JFrame implements Runnable {

    static final int WIDTH = 500;
    static final int HEIGHT = 500;
    static final String title = "East Game Development";

    private boolean running = false;
    private Thread thread;

    GameWindow() {
        setSize(new Dimension(WIDTH, HEIGHT));
        getContentPane().setBackground(Color.BLACK);
        setMaximumSize(new Dimension(WIDTH, HEIGHT));
        setMinimumSize(new Dimension(WIDTH, HEIGHT));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle(title);
        setResizable(false);
        setVisible(true);
    }

    private synchronized void start() {
        System.out.println("Debugging start method");
        if (running) {
            return;
        }
        running = true;
        thread = new Thread();
        thread.start();
    }

    private synchronized void stop() {
        if (!running) {
            return;
        }
        running = false;
        try {
            thread.join();
        } catch (Exception ex) {
        }
        System.exit(1);
    }

    @Override
    public void run() {
        System.out.println("Debugging");
        while (running) {
            System.out.println("Working well...");
        }
        stop();
    }

    public static void main(String[] args) {
        GameWindow gw = new GameWindow();
        gw.start();
    }

}

4 个答案:

答案 0 :(得分:4)

thread = new Thread();
thread.start();

你正在创建一个线程而不传递任何东西来运行。 Thread构造函数需要一个Runnable作为参数,这个runnable将在线程中执行。你想要

thread = new Thread(this);
thread.start();

但请注意,您的代码不是线程安全的:run()方法在没有同步的情况下读取running变量的值。如果在另一个线程中调用了stop()方法,它可能因此看起来是真的。您应该使用标准中断机制来请求您的线程停止,并检查该线程是否必须继续运行:

public void stop() {
    thread.interrupt();
}

public void run() {
    while (!Thread.currentThread.isInterrupted()) {
        ...
    }
}

答案 1 :(得分:2)

创建线程时,应指定它将调用哪个可运行的实例run。在你的情况下:

thread = new Thread(this);
thread.start();

答案 2 :(得分:1)

thread = new Thread();

您正在创建正常的线程并启动它。为什么你期望你的run()方法运行?

private synchronized void start() {
    System.out.println("Debugging start method");
    if (running) {
        return;
    }
    running = true;
    thread = new Thread(this);
    thread.start();
}

答案 3 :(得分:0)

如果你只有JFrame没有真正需要让它成为可运行的。只需在main方法中使用这些:

gw.setVisible(true);
gw.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);